본문 바로가기

Algorithm

스택(Stack)

Stack 

  • 겹겹이 쌓음이라는 의미
  • 데이터를 일시적으로 저장  
  • Last in First Out 형식 
  • 접근은 언제나 목록의 끝에서 발생 
  • push - 데이터를 넣는 작업
  • pop - 데이터를 꺼내는 작업 
  • top - 푸쉬와 팝을 하는 위치
  • bottom - 스택의 가장 아랫부분 

 

사용법 

 

ex)  Stack을 import해서 사용하기 

 

import java.util.Stack;
Stack<Integer> stack = new Stack<>();
Stack<String> stack = new Stack<>();
//값추가
stack.push();
//값삭제
stack.pop();
//값 초기화 
stack.clear();

 

ex) Stack 클래스 만들기 

 

public class IntStack {
    private int max;    //  스택 용량
    private int ptr;    //  스택 포인터
    private int[] stk;  //  스택 본체

    // 실행 시 예외: 스택이 비어 있음
    public class EmptyIntStackException extends RuntimeException {
        public EmptyIntStackException() {}
    }

    // 실행 시 예외: 스택이 가득 참
    public class OverflowIntStackException extends RuntimeException {
        public OverflowIntStackException() {}
    }

    // 생성자
    public IntStack(int capacity) {
        ptr = 0;
        max = capacity;
        try {
            stk = new int[max];
        } catch(OutOfMemoryError e) {       // 생성할 수 없을 때
            max = 0;
        }
    }

    // 스택에 x 넣기
    public int push(int x) throws OverflowIntStackException {
        if(ptr >= max) {
            throw new OverflowIntStackException();
        }
        return stk[ptr++] = x;
    }

    // 스택에 값 빼기 ( 꼭대기에 있는 데이터 꺼냄 )
    public int pop() throws EmptyIntStackException {
        if ( ptr <= 0 ) {
            throw new EmptyIntStackException();
        }
        return stk[--ptr];
    }

    // peak ( 꼭대기에 있는 값 확인 )
    public int peek() throws EmptyIntStackException {
        if(ptr <= 0) {
            throw new EmptyIntStackException();
        }
        return stk[ptr - 1];
    }


    // 스택에서 x 찾는 인덱스를 반환
    public int indexOf(int x) {
        for (int i = ptr - 1 ; i >= 0 ; i++) {
            if (stk[i] == x) {
                return i;
            }
        }
        return -1;
    }

    // 스택을 비움
    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("스택이 비어있습니다.");
        } else {
            for(int i = 0 ; i < ptr ; i++) {
                System.out.println(stk[i]);
            }
            System.out.println();
        }
    }

}

 

 

 

 

 

 

 

 

'Algorithm' 카테고리의 다른 글

재귀 알고리즘  (0) 2022.06.18
큐(Queue)  (0) 2022.06.08
Arrays.binarySearch  (0) 2022.06.06
검색(선형 검색, 보초법,이진 검색  (0) 2022.06.06
다차원배열과 확장 for문의 장점  (0) 2022.06.06