본문 바로가기
알고리즘 && 자료구조

[java] 직접 구현해보는 큐

by bloodFinger 2021. 3. 21.
public class IntQueue {
	private int max; //큐 용량
	private int front; //첫번째 요소 커서
	private int rear; //마지막 요소 커서
	private int num; // 현재 데이터수
	private int[] que; // 본체
	
	
	public class EmptyIntQueueException extends RuntimeException {
		public EmptyIntQueueException() {
			System.out.println("큐가 비어있습니다.");
		}
	}
	
	public class OverflowIntQueueException extends RuntimeException {
		public OverflowIntQueueException() {
			System.out.println("큐가 차있습니다. ");
		}
	}
	
	//생성자
	public IntQueue(int capacity) {
		num = front = rear = 0;
		this.max = capacity;
		
		try {
			que = new int[max];
		} catch (OutOfMemoryError e) {
			max=0;
		}
				
	}
	
	//데이터 삽입
	public void enqueue(int val) throws OverflowIntQueueException {

		//que에 데이터가 모두 찼을경우
		if(num >= max) {
			throw new OverflowIntQueueException();
		}
		
		que[rear++] = val;
		
		if(rear == max ) rear = 0;
		
		//데이터 하나 생성
		num++;
	}
	
    //데이터 삭제
	public int dequeue() throws EmptyIntQueueException {
		if(num <= 0) {
			throw new EmptyIntQueueException();
		}
		
		int k = que[front++];
		
		num--;
		if(front == max) front = 0;
				
		return k;
	}
    
	//맨앞의 데이터
	public int peek() {
		if(num <= 0)
			throw new EmptyIntQueueException();
		return que[front];
	}
	
	//요소 파악
	public int indexOf(int x) {
		for (int i = 0; i < num; i++) {
			int idx = (i + front) % max;
			if(que[idx] == x) {
				return idx;
			}
		}
		return -1;
	}
	
}
​

 

 

 

 

'알고리즘 && 자료구조' 카테고리의 다른 글

Disjoint Set(서로수 집합)  (0) 2020.07.29
브루트 -포스법  (0) 2020.07.28
[스터디] 검색 알고리즘  (0) 2020.07.14
백준 2606 - BFS(Breadth-First-Search)  (0) 2020.06.08
퀵 정렬( Quick Sort ) 알고리즘  (0) 2020.06.04