JAVA - Queue이란? 그리고 구현

JAVA - Queue이란? 그리고 구현

728x90

Queue 란

Stack과 다르게 데이터가 들어간 순서대로 나오는 즉 FIFO(First In First Out) 자료구조입니다.

offer() 순차 보관

poll() 가장 먼저 보관되어 있는 값 추출

peek() 가장 먼저 보관되어 있는 값 확인

Queue 구현 코드

public class Queue { private int size = 2; private int head; private int tail; private int[] elements; public Queue() { this.head = 0; this.tail = 0; this.elements = new int [size]; } public boolean isEmpty(){ return head == tail; } public boolean isFull(){ if(tail == elements.length){ return true; } return false; } public void offer(int data){ if(isFull()){ size = tail + 5; int [] extendElements = new int[size]; for (int i = 0; i < tail; i++) { extendElements[i] = elements[i]; } elements = extendElements; } this.elements[tail++] = data; } public int poll(){ if (isEmpty()) { System.out.println("데이터가 존재하지 않습니다."); return -1; } int result = elements[head++]; return result; } public int peek(){ if(isEmpty()){ System.out.println("데이터가 존재하지 않습니다."); return -1; }else{ int result = this.elements[head]; return result; } } public void print(){ while (tail - head > 0) { System.out.println(elements[head]); head++; } } }

public class QueueExample { public static void main(String[] args) { Queue queue = new Queue(); queue.offer(1); System.out.println("poll() --> " + queue.poll()); // 1 queue.offer(2); queue.offer(3); queue.offer(4); System.out.println("peek() --> " + queue.peek()); // 2 queue.offer(5); queue.print(); // 2 // 3 // 4 // 5 } }

728x90

from http://kdg-is.tistory.com/232 by ccl(A) rewrite - 2022-01-01 01:27:59