[자료구조] Stack과 Queue

정은아·2024년 1월 1일
post-thumbnail

자료구조 Stack과 Queue에 대해 알아보자!

Stack(스택)

  • Stack은 후입선출 LIFO구조를 띈다.(Last-In-First-Out)
  • add(=push)로 값을 더할 수 있다.
  • pop(=remove)로 값을 빼낼 수 있다.
  • 주로 사용하는 메서드는 add(=push), pop(=remove), isEmpty()가 있다.
  • ex.
        Stack<String>stack = new Stack<>();

        stack.push("안녕");
        stack.add("하세요");
        stack.push("잘 있어요~~");
        stack.pop();
        stack.add("다시 만나요");

        while(!stack.isEmpty()){
            String str = stack.pop();
            System.out.println(str);
        }

Queue(큐)

  • Queue는 선입선출 FIFO구조를 띈다.(First-In-First-Out)
  • add(=offer)로 값을 더할 수 있다.
  • poll(=remove)로 값을 빼낼 수 있다.
  • 주로 사용하는 메서드는 add(=offer),poll(=remove),isEmpty()가 있다.
  • ex.
    public static void main(String[] args) throws Exception {
       Queue<Integer> queue = new LinkedList<>();

		queue.add(2);
        queue.add(4);
        queue.add(7);
        queue.offer(1);

        while(!queue.isEmpty()){
            int a = queue.poll();

            System.out.println(a);
        }

Deque(디큐)

  • Deque는 addFirst(=offerFirst)와 addLast(=offerLast)를 사용해 순서를 조작할 수 있다.
  • addFirst()하면 무조건 값이 왼쪽에, addLast()하면 무조건 값이 오른쪽에 온다.
  • Deque는 거의 사용되지 않는다.
  • ex.
  Deque<Integer> deque = new ArrayDeque<>();

       deque.addFirst(1);
       deque.offerFirst(2);
       deque.addLast(3);
       deque.offerLast(4);

       while (!deque.isEmpty()){
          int a = deque.pollFirst();
          System.out.println(a);
          
          a = deque.pollLast();
          System.out.println(a);
      }

profile
꾸준함의 가치를 믿는 개발자

0개의 댓글