Skills/Algorithm
알고리즘 Java 큐
개발자 윤구나
2023. 8. 11. 10:42
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
// command + shift + o => 자동 import 처리
public class Main {
public static void main(String[] args) {
// Queue
// 1. ArrayList
MyQueue queue = new MyQueue();
queue.enqueue("아이스아메리카"); // 1
queue.enqueue("아이스돌체라떼"); // 2
queue.enqueue("콜드브루"); // 3
// System.out.println(queue.peek());
// 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());
// 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());
}
}
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); // 0번째 인덱스의 값을 삭제
return x;
}
}