본문 바로가기
FullStack/21. Java

[알고리즘] 선형 Queue.

by nakanara 2014. 3. 24.
반응형
알고리즘 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());
        }
    }
}
 




반응형

'FullStack > 21. Java' 카테고리의 다른 글

[알고리즘] 퀵정렬  (0) 2014.04.02
[알고리즘] 링크리스트  (0) 2014.03.24
[알고리즘] Stack  (0) 2014.03.24
META-INF 폴더  (0) 2013.03.27
SpringWeb 소스 JUNIT 을 이용한 테스트  (0) 2013.03.14