Queue

Fox·2023년 12월 18일
post-thumbnail

Queue란?

정의

스택과 다르게 줄을 지어 순서대로 처리되는 자료구조이다.

  • 큐는 데이터를 일시적으로 쌓아두기 위한 자료구조로 FIFO(First In First Out) 선입선출의 형태를 가진다.
  • LinkedList를 사용하기 때문에 Queue와 LinkedList를 모두 Import 해야 한다.
  • 큐는 한쪽 끝은 프런트(front)로 정하여 삭제 연산만 수행함
  • 다른 한쪽 끝은 리어(rear)로 정하여 삽입 연산만 수행함
  • 컴퓨터 버퍼에서 주로 사용, 마구 입력이 되었으나 처리를 하지 못할 때, 버퍼(큐)를 만들어 대기 시킴

가장 많이 사용되는 곳은

  1. 은행 업무
  2. 콜센터 고객대기
  3. 프로세스 관리
    ...


주요 메서드

메서드설명
queue.add()데이터 추가 반환 값(boolean): 삽입 성공 시 true / 실패 시  Exception발생
queue.offer()데이터 추가 반환 값(boolean): 삽입 성공 시 true / 실패 시 false 반환
queue.poll()데이터 삭제 queue에 첫번째 값을 반환하고 제거 비어있다면 null
queue.remove()데이터 삭제 queue에 첫번째 값 제거 반환 값(삭제된 value의 자료형): 삭제된 value / 공백 큐이면 Exception("NoSuchElementException") 발생
queue.clear()데이터 모든값 삭제 queue 초기화 반환값 void
queue.peek()데이터 첫번째 값 가져옴 queue의 첫번째 값 참조 반환값 큐 헤드에 위치한 value/공백이면 null
queue.size()queue 사이즈 크기 반환값 int
queue.contains("찾고싶은 value")찾고 싶음 value값이 있는지 확인 있을경우 true/ 없으면 false 반환값 boolean
queue.isEmpty();공백이면 true / 값이 있으면 false 반환값 boolean
queue.element();큐의 첫번째 값 반환 공백큐이면 Exception("NoSuchElementException")발생 반환값 큐 헤드에 위치한 value
queue.remove(삭제할 value);반환 값(boolean): 큐에 해당 value가 존재하면 해당 값 삭제 후 true / 존재하지 않으면 false 반환


Queue 사용

선언

  • 아래처럼 다양한 타입으로 Queue 선언 가능
// Queue 선언하기
Queue queue = new LinkedList(); // 타입설정 X Object로 입력  
Queue<Integer> q1 = new LinkedList<Integer>(); // Integer 타입으로 선언  
Queue<Integer> q2 = new LinkedList<>(); // new 부분 타입생략 가능  
Queue<Integer> q3 = new LinkedList<Integer>(Arrays.asList(1, 2, 3)); // 선언과 동시에 초기 값 세팅  
  
Queue<String> str = new LinkedList<String>(); // String타입 선언  
Queue<Character> ch = new LinkedList<Character>(); // Character타입 선언

값 추가

  • add와 offer가 있다.
  • 값 추가 실패 시 add는 IllegalStateException / offer는 false를 반환하기 때문에 offer를 사용하는 것이 더 좋다고 한다.
str.offer("Hello");  
str.offer("World");  
System.out.println(str); // 값 출력 [Hello, World]
str.clear();

값 삭제

  • poll() : 값이 있으면 첫 번째 값 출력하면서 삭제, 값이 없으면 NoSuchElementException반환
  • remove() : 값이 있으면 첫 번째 값 출력하면서 삭제, 값이 없으면 Null 리턴
  • clear() : Queue를 비운다.
str.offer("Hello");  
str.offer("World");  
str.offer("Hello");  
str.offer("Hello");  
str.offer("World");  
  
System.out.println(str); // 값 출력 [Hello, World, Hello, Hello, World]  
str.poll(); // 삭제  
System.out.println(str); // 값 출력 [World, Hello, Hello, World]  
str.remove(); // 삭제  
System.out.println(str); // 값 출력 [Hello, Hello, World]  
str.remove("Hello"); // 해당하는 값 삭제  
System.out.println(str); // 값 출력 [Hello, World]  
str.clear(); // 모두 삭제  
System.out.println(str); // 값 출력 []

크기 구하기

str.offer("Hello");  
str.offer("World");  
str.offer("Hello");  
str.offer("Hello");  
str.offer("World");  
  
System.out.println("Queue의 크기 : " + str.size()); // 값 출력 [Queue의 크기 : 5]
str.clear();

값 출력

  • peek() : 가장 앞에 있는 값부터 출력된다.
  • Iterator() : 모든 값을 출력한다.
str.offer("Hello");  
str.offer("World");  
str.offer("Hello");  
str.offer("Hello");  
str.offer("World");  
  
System.out.println("첫 번째 값 출력 : " + str.peek()); // 값 출력 [첫 번째 값 출력 : Hello]
  
/* Iterator 사용하여 모든 값 출력 */  
for (String s : str) {  
    System.out.print(s + " "); // 값 출력 [Hello World Hello Hello World]
}


Queue 예제

코드

Queue<Integer> que = new LinkedList<Integer>(); // Integer변수 생성  
int tmp = 0;  
  
for (int i = 1; i <= 5; i++) {  
    que.offer(i); // 값 추가  
}  
System.out.println(que);  
  
for (int i = 1; i <= 5; i++) {  
    tmp = que.peek(); // 첫 번째 값 return    que.offer(tmp); // 값 추가.  
    System.out.println(que.remove()); // 첫 번째 값 삭제 및 출력  
}
for (int i = 1 ; i <= 5 ; i++){  
    que.offer(i);  
}  
System.out.println(que);  
  
que.offer(que.poll()); // 첫 번째 값을 삭제하며 동시에 값 추가 (= 앞의 값을 가장 뒤로)  
System.out.println(que);
  • 바로 위 반복문은 삭제를 했지만 그보다 위 반복문은 삭제를 진행하지 않아
  • [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] 출력

결과

[1, 2, 3, 4, 5]
1
2
3
4
5
---------------------------------------
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
[2, 3, 4, 5, 1, 2, 3, 4, 5, 1]












참고 : https://coding-factory.tistory.com/602

profile
주니어개발자 Fox 입니다 🦊

0개의 댓글