본문 바로가기

자료구조와 알고리즘

Stack

늦게 들어온게 먼저 나간다

Stack은 queue와 반대로 LIFO 구조다. 즉 마지막에 들어온게 제일 먼저 나간다. 

Stack 클래스는 Vector 클래스를 확장하고, Collection, List와 같은 인터페이스들을 구현한다.

 

Stack의 주요 메소드는 push()와 pop()이다. 

Stack의 장점

 - 구현이 쉽다

-  데이터 저장 및 읽기 속도가 빠르다

 

Stack의 단점

- 데이터 크기를 미리 정해야 한다.

public class MakeQueue<T>  {

  public static void main(String[] args) {
    Stack<String> a = new Stack<String>();
    System.out.println(a.isEmpty());
    a.push("Hi");
    System.out.println(a.peek());
    a.pop();
    try{
    System.out.println(a.peek());} // stack이 비어있을 땐 RuntimeException인 EmptyStackException이 발생
    catch(EmptyStackException e) {
      e.printStackTrace();
      e.getMessage();

    }

      System.out.println(a.add("1"));
      System.out.println(a.add("2"));
      System.out.println(a.add("3"));
      System.out.println(a.pop()); // 마지막으로 온 값인 3을 리턴하고, 3 삭제
      System.out.println(a.peek()); // 그래서 마지막값이 2다.
    

  }
}
// ArrayList 사용해서 기능 직접 구현해보기

public class MakeQueue<T>  {
  ArrayList<T> stack = new ArrayList<T>();
  public void push(T data) {
    stack.add(data);
  }

  public T pop() {
    int size = stack.size();
    if(stack.isEmpty()) {
      return null;
    } T tmp = stack.get(size-1);
    stack.remove(size-1);
    return tmp;
  }

  public static void main(String[] args) {
    MakeQueue<Integer> a = new MakeQueue<Integer>();
    a.push(2);
    a.push(3);
    a.push(4);
    System.out.println(a.pop()); // 4
    System.out.println(a.pop()); // 3
    System.out.println(a.pop()); // 2
    System.out.println(a.pop()); // null
  }
}

'자료구조와 알고리즘' 카테고리의 다른 글

  (0) 2022.06.30
트리  (0) 2022.06.29
hash table  (0) 2022.06.28
Queue  (0) 2022.06.16
Arrays (배열)  (0) 2022.06.15