04. Queue

2020. 2. 2. 07:36CSE/Data Structure

* 특징

: 데이터를 일시적으로 쌓아 놓은 자료구조

  선입선출(FIFO, First In First Out)

 

* java로 간단하게 구현한 모습

public class Queue<T> {
    private int front;
    private int num;
    private int rear;
    private int max;
    private T[] que;

    public Queue(int n){
        front = num = rear = 0;
        max = n;
        try{
            que = (T[])(new Object[max]);
        }catch(OutOfMemoryError e){
            max = 0;
        }
    }

    public T enque(T x) throws OverflowQueueException{
        if(num>=max){
            throw new OverflowQueueException();
        }
        que[rear] = x;
        rear++;
        num++;
        if(rear==max){
            rear = 0;
        }
        return x;
    }

    public T deque() throws EmptyQueueException{
        if(num<=0){
            throw new EmptyQueueException();
        }
        T x = que[front];
        front ++;
        num--;
        if(front==max){
            front = 0;
        }

        return x;
    }

    public T peek() throws EmptyQueueException{
        if(num<=0){
            throw new EmptyQueueException();
        }
        return que[front];
    }

    public int indexOf(T x){
        for(int i = 0; i<num;i++){
            int idx = (i+front)%max;
            if(que[idx].equals(x)){
                return idx;
            }
        }
        return -1;
    }

    public void clear(){
        front = rear= num = 0;
    }

    public int capacity(){
        return max;
    }

    public int size(){
        return num;
    }

    public boolean isEmpty(){
        return num<=0;
    }

    public boolean isFull(){
        return num>=max;
    }

    public void dump(){
        if(num<=0){
            System.out.println("큐가 비어있습니다");
        }else{
            for(int i = 0; i<num;i++){
                int idx = (i+front)%max;
                System.out.printf(que[idx] + " ");
            }
            System.out.println();
        }
    }
}

class EmptyQueueException extends RuntimeException{
    public EmptyQueueException(){}
}

class OverflowQueueException extends RuntimeException{
    OverflowQueueException(){}
}

 

 

'CSE > Data Structure' 카테고리의 다른 글

Hash Table, ArrayList  (0) 2021.07.19
03. Stack  (0) 2020.01.21
02. 이진 검색(Binary Search)  (0) 2019.08.21
01. 선형 검색 (Linear Search)  (0) 2019.08.21