알고리즘

큐 구현하기 | ArrayList, LinkedList, ArrayDeque

김휴고 2023. 8. 10. 15:01

자바에서 큐Queue 자료 구조를 직접 지원하는 인터페이스는 없다.

대신 다음의 방법들로 큐를 쓸 수 있다.

 

1. ArrayList

  • ArrayList를 활용해 직접 queue 클래스를 만들기
class MyQueue {
	private List<String> list = new ArrayList<String>(); // private 접근

	// 큐 안에 x라는 요소를 저장합니다.
	public void enqueue(String x) {
		list.add(x); // 내부에 이미 생성된 리스트의 add(맨 끝에 저장)
	}

	// 맨 앞의 요소를 반환 (index 0)
	public String peek() {
		return list.get(0); // 들어간지 가장 오래
	}

	// 맨 앞의 요소를 반환하고 제거
	public String dequeue() {
		String x = list.get(0);
		list.remove(0);
		return x;
	}
}
  • 실행문
public class Q_ArrayList {

	public static void main(String[] args) {
		/*
		 * Queue 1. ArrayList로 구현하기
		 */

		MyQueue queue = new MyQueue();
		queue.enqueue("아이스 아메리카노");
		queue.enqueue("아이스 돌체라떼");
		queue.enqueue("콜드브루 따뜻하게");
		System.out.println(queue.peek());
		System.out.println(queue.dequeue());
		System.out.println(queue.peek());
	}

}
  • 실행결과

그러나 이 방법은 주로 사용되진 않는다.

 

2. LinkedList

import java.util.LinkedList;

public class Q_LinkedList {

	public static void main(String[] args) {
		// 2. LinkedList
		LinkedList<String> queue2 = new LinkedList<>();
		// enqueue -> 새롭게 줄서기 => add
		// dequeue -> 가장 오래선 사람 집에 보내기 => poll
		// 누가 가장 오래 섰나? -> peek
		queue2.add("아이스아메리카노"); // 1
		queue2.add("아이스돌체라떼"); // 2
		queue2.add("콜드브루 따뜻하게"); // 3
		System.out.println(queue2);
		System.out.println(queue2.poll());
		System.out.println(queue2);
		System.out.println(queue2.poll());
		System.out.println(queue2);
		System.out.println(queue2.poll());
		System.out.println(queue2);
	}

}
  • 실행결과

3. ArrayDeque

import java.util.ArrayDeque;

public class Q_ArrayDeque {

	public static void main(String[] args) {
		// 3. ArrayDeque
		ArrayDeque<String> queue3 = new ArrayDeque<>();
		queue3.add("아이스아메리카노"); // 1
		queue3.add("아이스돌체라떼"); // 2
		queue3.add("콜드브루 따뜻하게"); // 3
		System.out.println(queue3);
		System.out.println(queue3.poll());
		System.out.println(queue3);
		System.out.println(queue3.poll());
		System.out.println(queue3);
		System.out.println(queue3.poll());
		System.out.println(queue3);

	}

}
  • 실행결과