본문 바로가기

자료구조와 알고리즘

Queue

큐는 FIFO다. 먼저 들어오면 먼저 나간다. 음식점에 대기줄을 생각해보면 된다. 먼저 줄에 있는 사람이 먼저 들어갈 수 있다. 

 

자바에서 Queue는 Collection<E>를 확장한 interface 다. Queue를 구현한 대표적인 클래스에는 LinkedList가 있다. 

Queue에 정의되어 있는 메소드는 요소를 추가하는 offer(e), 맨 앞에 있는 요소를 제거하는 poll(), 맨 앞에 있는 요소를 보는 peek()가 있다.

 

import java.util.*;

//enqueue와 dequeue, peek 구현해보기
public class MakeQueue<T>  {
  private ArrayList<T> a = new ArrayList<T>();
  public Queue<T> b = new LinkedList<T>();

  public void enqueue(T data) {
    a.add(data);
  }

  public T dequeue () {
    if(a.isEmpty() ) {
      return null;
    } return a.remove(0);
  }

  public T peek() {
    if(a.isEmpty()) {
      return null;
    }
    return a.get(0);
  }

  public static void main(String[] args) {

    MakeQueue<String> a = new MakeQueue<String>();
    a.b.poll();
    //Queue이기 때문에 0: 1, 1: 2, 2: 3;
    a.enqueue("1");
    a.enqueue("2");
    a.enqueue("3");
    
    System.out.println(a.peek()); // 가장 먼저 입력된 값인 1이 출력
    
    System.out.println(a.dequeue()); // 1 삭제
    System.out.println(a.dequeue()); // 2 삭제
    System.out.println(a.dequeue()); // 3 삭제


  }
}

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

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