하지의 코딩일지/STUDY MEMO[BACKEND]
큐 (Queue)
하지마지
2023. 7. 11. 15:53
728x90
@ 선입 선출 ( First In First Out : FIFO) 자료구조
- 먼저 들어온 데이터가 먼저 나가는 구조
@ 입력 순서대로 데이터 처리가 필요할 때 사용
-프린터 출력 대기열 BFS(Breath-First Search)등
큐 기본 구조
- 선입선출 구조를 따름
- 기본적으로 데이터 추가, 꺼내기, 큐 공간 확인 동작으로 이루어짐
큐 기본 연산
데이터 추가(Enqueue)
-큐에 데이터 추가
데이터 빼기(Dequeue)
- 큐에서 데이터 빼기
import java.util.LinkedList;
import java.util.Queue;
public class Main {
public static void main(String[] args) {
Queue queue = new LinkedList();
queue.add(1);
queue.add(2);
queue.add(3);
queue.add(4);
queue.add(5);
System.out.println(queue);
System.out.println(queue.poll());
System.out.println(queue);
System.out.println(queue.poll());
System.out.println(queue);
System.out.println(queue.poll());
System.out.println(queue);
System.out.println(queue.contains(3));
System.out.println(queue.size());
System.out.println(queue.isEmpty());
queue.clear();
System.out.println(queue);
System.out.println(queue.poll());
}
}
import java.util.Queue;
public class Main {
public static void main(String[] args) {
Queue queue = new LinkedList();
queue.add(1);
queue.add(2);
queue.add(3);
queue.add(4);
queue.add(5);
System.out.println(queue);
System.out.println(queue.poll());
System.out.println(queue);
System.out.println(queue.poll());
System.out.println(queue);
System.out.println(queue.poll());
System.out.println(queue);
System.out.println(queue.contains(3));
System.out.println(queue.size());
System.out.println(queue.isEmpty());
queue.clear();
System.out.println(queue);
System.out.println(queue.poll());
}
}
add() : 데이터를 큐에 추가한다.
쿠에 데이터를 더 이상 추가할 수 없으면 예외를 발생시킨다
offer(): 데이터를 큐에 추가한다
큐에 데이터를 더 이상 반환할 수 없으면 false로 반환한다 (add보다 offer를 권장)
poll() : 큐에 맨 처음 들어간 데이터를 꺼낸다.
스택의 pop()과 달리 큐가 비어있다면 예외가 아닌 null을 반환한다.
peek() : 큐에 맨 처음 들어간 데이터를 확인한다.
스택의 peek()과 달리 큐가 비어 있다면 예외가 아닌 null을 반환한다.
isEmpty() : 큐가 비어있으면 true, 아니면 false를 반환한다.
size() : 큐에 들어있는 데이터의 개수를 반환한다.
clear() : 큐에 들어있는 모든 데이터를 삭제한다.
728x90