ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [자료구조] 3-1. 큐(Queue)
    CS/자료구조 2022. 9. 10. 16:33
    반응형
    728x90

     

    자료구조도

     

    이미지 출처: https://greatzzo.tistory.com/43

     

    이 글에서는 Queue에 대해서만 알아보고, 우선순위 큐(Priority Queue)는 다음에 알아보도록 하자.

    Queue의 특징

    FIFO(First In First Out) 구조로 먼저 들어온 데이터가 먼저 나가는 구조를 갖는다(ex) 줄서기).

    이는 스택(Stack)의 FILO(First In Last Out)와 반대되는 구조이다.

    Enqueue는 큐에 데이터를 넣는 기능을 뜻하고, Dequeue는 데이터를 꺼내는 기능을 뜻한다.

     

    이미지 출처: https://velog.io/@gillog/%ED%81%90Queue

     

    Queue 선언과 메소드

    Queue 클래스를 쓰기 위해선 LinkedList 클래스도 같이 사용해야한다.

    LinkedList는 다음에 알아보도록 하자.

     

    - Queue<String> strQueue = new LinkedList<>();
    - add(obj) / offer(obj)
    - remove() / poll()
    - isEmpty()
    - size()

     

    선언할 때 Queue와 LinkedList를 사용하여 Queue를 선언한다.

    import java.util.LinkedList;
    import java.util.Queue;
    
    public class QueueExample {
        public static void main(String[] args) {
            
            // Queue 선언
            Queue<String> strQueue = new LinkedList<>();
        }
    }

     

    * Enqueue

    값을 추가할 때에는 add와 offer 메소드 중 하나를 사용한다.

    cf) size()를 통해 queue 크기를 알 수 있다.

    // 값 추가 - 리턴타입 boolean
    strQueue.add("banana");
    strQueue.offer("apple");
    
    // 값 출력
    System.out.println(strQueue); // [banana, apple]
    
    // Queue 크기
    System.out.println(strQueue.size()); // 2

     

    * Dequeue

    값을 꺼낼 때에는 remove와 poll 메소드 중 하나를 사용한다.

    // 값 꺼내기
    System.out.println(strQueue.remove()); // banana
    System.out.println(strQueue); // [apple]
    
    System.out.println(strQueue.poll()); // apple
    System.out.println(strQueue); // []

     

    isEmpty() 메소드로 Queue가 비어있는 지 확인할 수 있다.

    // Queue가 비어있는 지 확인 - 리턴타입 boolean
    System.out.println(strQueue.isEmpty());  // ture
    728x90
Designed by Tistory.