nakanara
2014. 3. 24. 16:34
알고리즘 Queue
package com.nakanara.queue;
public class Queue { private static int MAX_SIZE = 5; private int data[] = new int[MAX_SIZE]; private int head = 0; // 입력 기준점 private int tail = 0; // 읽은 기준점
/** * 데이터 입력. * @param val */ private void put(int val) throws Exception { // 시작과 끝의 차이의 최대치가 초과될 경우 입력이 불가. if((head-tail) >= MAX_SIZE) { throw new Exception("자료 입력 공간이 없습니다."); } data[head%MAX_SIZE] = val; ++head; } /** * 데이터 읽기. * @return */ private int get() throws Exception{ if((head-tail) == 0) { throw new Exception("읽을 데이터가 없습니다."); } int result = data[tail%MAX_SIZE]; ++tail; return result; }
@Override public String toString() { StringBuffer buffer = new StringBuffer(); for(int i=tail; i < head; i++) { int result = data[i%MAX_SIZE]; buffer.append(i).append("=").append(result).append("|"); } return buffer.toString(); } public static void main(String args[]) { Queue queue = new Queue(); try { queue.put(1); queue.put(2); queue.put(3); queue.put(4); queue.put(5); queue.put(6); queue.get(); queue.put(6); System.out.println(queue.toString()); }catch(Exception e){ System.out.println(e.getMessage()); } } } |