Queue(by Array) 구현 코드

한시삼십사분·2022년 1월 11일

자료구조 JAVA

목록 보기
10/16
post-thumbnail

Queue Interface

package Interface_form;

public interface Queue<E> {
	
	/**
	 * 
	 * @param data queue에 추가할 요소
	 * @return 정상적으로 추가되었을 때 true 반환
	 */
	boolean offer(E data);
	
	/**
	 * queue의 첫번 째 요소를 삭제하고 해당 요소를 반환
	 * @return queue의 첫번 째 요소
	 */
	E poll();
	
	/**
	 *	queue의 첫번 째 요소를 삭제하지 않고 반환
	 * @return Queue의 첫번 쨰 요소
	 */
	E peek();
}

ArrayQueue class

import java.util.NoSuchElementException;

import Interface_form.Queue;

public class ArrayQueue<E> implements Queue<E> {
	private static final int DEFAULT_CAPACITY = 64;
	
	private Object[] array;
	private int size; 
	
	private int front;
	private int rear;
	
	//생성자 1
	public ArrayQueue() {
		this.array = new Object[DEFAULT_CAPACITY];
		size = 0;
		front = 0;
		rear = 0;
	}
	
	//생성자 2
	public ArrayQueue(int capacity) {
		this.array = new Object[capacity];
		size = 0;
		front = 0;
		rear = 0;
	}
	
	private void resize(int newCapacity) {
		int currCapacity = array.length;
		
		Object[] newArray = new Object[newCapacity];
		
		for(int i=0, j = front+1; i<=size; i++, j++) {
			newArray[i] = array[j % currCapacity];
		}
		this.array = null;
		this.array = newArray;
		
		this.front = 0;
		this.rear = size;
	}
	
	@Override
	public boolean offer(E data) {
		if((this.rear+1) % array.length == this.front) {
			resize(array.length*2);
		}
		rear = (rear+1) % array.length;
		
		array[rear] = data;
		size++;
		
		return true;
	}
	
	@Override
	public E poll() {
		if(size == 0) {
			return null;
		}
		
		front = (front+1) % array.length;
		@SuppressWarnings("unchecked")
		E element = (E) array[front];
		
		array[front] = null;
		size--;
		
		
		if(array.length>DEFAULT_CAPACITY && size< (array.length/4)) {
			resize(Math.max(array.length/2, DEFAULT_CAPACITY));
		}
		
		return element;
		
	}
	
	public E remove() {
		E item = poll();
		
		if(item == null) {
			throw new NoSuchElementException();
		}
		
		return item;
	}
	
	@SuppressWarnings("unchecked")
	public E peek() {
		if(size == 0) {
			return null;
		}
		
		return (E) array[(front+1) % array.length];
	}
	
	public E element() {
		E item = peek();
		
		if(item == null) {
			throw new NoSuchElementException();
		}
		
		return item;
	}
	
	public int size() {
		return this.size;
	}
	
	public boolean isEmpty() {
		return size==0;
	}
	
	public boolean contains(E data) {
		int start = (front+1) % array.length;
		
		for(int i=0, idx = start; i<size; i++, idx = (idx+1) % array.length) {
			if(data.equals(array[idx])) {
				return true;
			}
		}
		
		return false;
	}
	
	public void clear() {
		for(int i=0; i<size; i++) {
			array[i] = null;
		}
		
		size = 0;
		front = rear = 0;
	}
	
}

https://st-lab.tistory.com/161?category=856997
내가 직접 코딩해보고 사이트를 확인하여 수정하는 방법으로 구현을 진행했음

profile
인간은 망각의 동물이라지만 이건 너무한 거 아니냐고

0개의 댓글