Data Structure

[Data Structure] Java μŠ€νƒ(Stack) μ‚¬μš©

An effort will never betray 😎 2021. 1. 15. 13:53
λ°˜μ‘ν˜•
  • 이 글은 "온라인 μžλ°” μŠ€ν„°λ”” λ‚΄μš©"을 μ •λ¦¬ν•œ κΈ€μž…λ‹ˆλ‹€.

Stackμ΄λž€?

  • μŠ€νƒμ€ 책을 μŒ“λŠ” κ²ƒμ²˜λŸΌ 데이터λ₯Ό 담을 수 μžˆλŠ” 자료ꡬ쑰 μž…λ‹ˆλ‹€.

  • μŠ€νƒμ˜ κ°€μž₯ 큰 νŠΉμ§•μ€ First In Last Out (FILO) ꡬ쑰λ₯Ό 가지고 μžˆμŠ΅λ‹ˆλ‹€.


λ°°μ—΄λ‘œ μŠ€νƒ κ΅¬ν˜„

public class Stack {

    final int MAX_SIZE = 100;
    int arr[];
    int size;

    public Stack(){
        arr = new int[MAX_SIZE];
        size = 0;
    }

    public void push(int data){
        if(size<MAX_SIZE){
            arr[size++] = data;
        }
    }

    public int pop(){
        if(size>0){
            size--;
            return 1;
        }
        return 0;
    }

    public int top(){
        if(size>0){
            return arr[size-1];
        }
        return -1;
    }

    public boolean isFull(){
        if(size == MAX_SIZE){
            return true;
        }
        return false;
    }
}
public class Main {
    public static void main(String[] args) {
        Stack stack = new Stack();
        stack.push(1);
        stack.push(2);
        stack.push(3);

        System.out.println(stack.top());        // 3
        stack.pop();
        System.out.println(stack.top());        // 2
        stack.pop();
        System.out.println(stack.top());        // 1
        stack.pop();
    }
}

λ…Έλ“œλ‘œ μŠ€νƒ κ΅¬ν˜„

public class ListNode {
    int data;
    ListNode next;

    public ListNode(int data) {
        this.data = data;
        next = null;
    }
}

λ‹€μŒ ν΄λž˜μŠ€λŠ” λ…Έλ“œλ₯Ό κ΅¬ν˜„ν•˜λŠ” μ½”λ“œμž…λ‹ˆλ‹€.

public class ListNodeStack {

    ListNode head;
    int size;

    public ListNodeStack() {
        head = null;
        size = 0;
    }

    void push(int data){
        ListNode node = head;
        if(size == 0){
            node = new ListNode(data);
            head = node;
        }
        else{
            while(node.next != null){
                node = node.next;
            }
            node.next = new ListNode(data);
        }
        size++;
    }

    int pop(){
        ListNode node = head;
        int data;
        if(size == 1){
            data = node.data;
            node = null;
            head = node;
        }
        else{

            while(node.next.next!=null){
                node = node.next;
            }
            data = node.next.data;
            node.next = null;
        }
        size--;
        return data;
    }

    public int getSize() {
        return size;
    }
}
public class Main {
    public static void main(String[] args) {

        ListNodeStack stack = new ListNodeStack();
        stack.push(1);
        stack.push(2);
        stack.push(3);

        System.out.println(stack.getSize());        // 3

        System.out.println(stack.pop());        // 3
        System.out.println(stack.pop());        // 2
        System.out.println(stack.pop());        // 1
    }
}
λ°˜μ‘ν˜•