ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 큐 구현
    자료구조 2022. 3. 29. 15:22
    public class Queue {
        private int max;
        private int front; 
        private int rear;
        private int num; //현재 큐에 들어있는 수들의 개수
        private int[] que;
        
        public class EmptyQueueException extends RuntimeException {
            
        }
        
        public class OverflowQueueException extends RuntimeException {
            
        }
        
        public Queue(int capacity) {
            max = capacity;
            front = 0;
            rear = 0;
            num = 0;
            try {
                que = new int[max];
            }catch (OutOfMemoryError e) {
                max = 0;
            }
        }
        
        public int enqueue(int x) throws OverflowQueueException {
            if (num >= max)
                throw new OverflowQueueException();
            que[rear++] = x;
            num++;
            if (rear == max) { 
                rear = 0;
            }
            return x;
        }
        
        public int dequeue() throws IntStack.EmptyStackException {
            if (num <= 0)
                throw new EmptyQueueException();
            int x = que[front++];
            num--;
            if (front == max)
                front = 0;
            return x;
        }
        
        public int peek() throws EmptyQueueException{ //프론트 데이터 조회 
            if (num <= 0)
                throw new EmptyQueueException();
            return que[front];
        }
        
        public int indexOf(int x) { //x가 큐 안에 있는지 검색
            for (int i = 0; i < num; i++) {
                int idx = (i + front) % max;
                if (que[idx] == x) 
                    return idx;
            }
            return -1;
        }
        
        public void clear() {
            num = front = rear = 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++) {
                    System.out.println(que[(i+front) % max] + " ");
                }
                System.out.println();
            }
        }
    }

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

    Array와 LinkedList의 차이  (0) 2023.01.05
    자료구조란? Data Structure  (0) 2023.01.04
    Deque(덱, 데크) - 자바  (0) 2022.08.06
    스택 구현  (0) 2022.03.29
Designed by Tistory.