취준/JAVA

QUEUE

JuneBee 2022. 5. 18. 10:42
728x90
반응형

특성

  1. 스택과 마찬가지로 삽입과 삭제의 위치가 제한적인 자료구조
  2. 선입 선출 구조 (First In First Out)
    큐에 삽입한 순서대로 원소가 저장되며, 가장 먼저 삽입된 원소가 가장 먼저 삭제됨
  3. 기본 연산 : enQueue, deQueue 주요 메서드: offer(), poll(), isEmpty(), size(), peek()
  4. 주로 LinkedList 클래스를 Queue 인터페이스의 구현체로 많이 사용한다
🤦🏻‍♀️ 큐 안에 아무것도 없을 떄, 스택과 마찬가지로
   poll() : 삭제 - 를 불렀을 때, 예외 발생 처리가 없다
   remove() : 삭제 - 를 불렀을 때, 예외가 발생한다

예시

import jvava.util.Queue;
import java.util.LinkedList;
public class QueueTest{
public static void main(String [] args){
int N = 10;
Queue <int[]> queue = new LinkedList<>(); //손님 번호, 붕어빵 갯수
int customer = 1;

queue.offer(new int[] {customer, 1});
while (N >0){
	if(!queue.isEmpty()){
		int[] p = queue.poll();
		int buyable = (N>p[1])? p[1]: N; //살수있는 붕어빵 수
		N -= buyable ; //팔린 갯수
		if(N==0){//전부 팔림
		System.out.println("마지막 손님: "+ p[0] +"사간 갯수: "+buyable); }
		else{
		System.out.println(p[0]+"번 손님이 " + buyable+ "만큼 붕어빵을 사갔습니다\\n남은개수: "+N);
		p[1] ++; //사려는 붕어빵 증가
		queue.offer(p);
		queue.offer(new int[] {++customer,1});	}
  }//end of isEmpty
} //end of while
} //end of main
} //end of class

 

728x90
반응형