MapleStory Cookie With Halo

☕ JAVA/☕ 개념지식

[JAVA] Stack, 호출스택

뉴이 NUEY 2024. 10. 31. 18:51
반응형

 

Stack

 


 

호출 스택
 call stack

 

main메서드가 println메서드를 호출하는 과정.

 

  • 메서드 수행에 필요한 저장공간(memory place)

  • 메서드가 호출call되면 호출스택에 메모리를 할당하고, 끝나면 해제.

  • 이와 같이 후입선출 Last In First Out(LIFO)로 나중에 넣은 데이터를 먼저 꺼냅니다.

 

  1. project 시작
  2. main메서드 실행.
  3. println 호출 → main 대기.
  4. println 수행 종료/삭제됨 → call stack 삭제.
  5. main 다시 실행.
  6. main 에 있는 코드 모두 끝날 시 main메서드도 삭제 됨
  7. project 종료.

 


 

  • 데이터를 넣는 작업을 Put

  • 데이터를 꺼내는 작업을 Pop 이라 합니다.

배열로 스택을 만들어보면 이렇습니다.

더보기
package chap04;

public class IntStack {
    private int max;    // Stack size
    private int ptr;    // Stack pointer
    private int[] stk;  // Stack array

    // Exception: Stack is empty
    public class EmptyIntStackException extends RuntimeException {
        public EmptyIntStackException() {
        }
    }

    // Exception: Stack is full
    public class OverflowIntStackException extends RuntimeException {
        public OverflowIntStackException() {
        }
    }

    // Base Constructor
    public IntStack() {
    }

    // Constructor
    public IntStack(int capacity) {
        ptr = 0;
        max = capacity;
        try {
            stk = new int[max];         // Create stack array
        } catch (OutOfMemoryError e) {  // Stack allocation failed
            max = 0;
        }
    }

    public int push(int x) throws OverflowIntStackException {
        if (ptr >= max) {               // Stack is full
            throw new OverflowIntStackException();
        }
        return stk[ptr++] = x;         // Push x
    }

    public int pop() throws EmptyIntStackException {
        if (ptr <= 0) {                // Stack is empty
            throw new EmptyIntStackException();
        }
        return stk[--ptr];
    }
    
    public int peek() throws EmptyIntStackException {
        if (ptr <= 0) {                // Stack is empty
            throw new EmptyIntStackException();
        }
        return stk[ptr - 1];
    }
    
    public int indexOf(int x) {
        for (int i = ptr - 1; i >= 0; i--) {    // Search from top
            if (stk[i] == x) {
                return i;
            }
        }
        return -1;                              // x not found
    }

    public void clear() {
        ptr = 0;
    }
    
    public int capacity() {
        return max;
    }

    public int size() {
        return ptr;
    }
    
    public boolean isEmpty() {
        return ptr <= 0;
    }
    
    public boolean isFull() {
        return ptr >= max;
    }

    public void dump() {
        if (ptr <= 0) {
            System.out.println("Stack is empty.");
        } else {
            for (int i = 0; i < ptr; i++) {
                System.out.print(stk[i] + " ");
            }
            System.out.println();
        }
    }

}

 


참조 : https://www.youtube.com/watch?v=-mqL3LJ4iVc&list=PLW2UjW795-f6xWA2_MUhEVgPauhGl3xIp&index=62

반응형