数据结构与算法(二)用数组实现队列

public class ArrayQueue {

    int maxSize;//actual capacity is maxSize - 1, make an empty position as interval
    int front; // point to the first position
    int rear;//point to the position after the last position
    int[] array;

    public ArrayQueue(int maxSize){
        this.maxSize = maxSize;
        array = new int[maxSize];
    }

    public boolean isFull(){
        return (rear + 1) % maxSize == front;
    }

    public boolean isEmpty(){
        return rear == front;
    }

    public boolean offer(int num){
        if (isFull()){
            System.out.println("Queue is full.");
            return false;
        }
        array[rear] = num;
        rear++;
        return true;
    }

    public int poll(){
        if (isEmpty()){
            throw new RuntimeException("Queue is Empty.");
        }
        int value = array[front];
        front++;
        return value;
    }

    public int peek(){
        if (isEmpty()){
            throw new RuntimeException("Queue is Empty.");
        }
        return array[front];
    }

    public int size(){
        return (rear + maxSize - front) % maxSize;
    }

    public void printAll() {
        if (isEmpty()){
            System.out.println("[]");
            return;
        }
        StringBuffer sb = new StringBuffer();
        sb.append("[");
        for (int i = front; i < front + size(); i ++) {
            sb.append(array[i % maxSize]);
            sb.append(",");
        }
        sb.deleteCharAt(sb.lastIndexOf(","));
        sb.append("]");
        System.out.println(sb);
    }



    public static void main(String[] args) {
        ArrayQueue queue = new ArrayQueue(4);
        //add data
        queue.offer(1);
        queue.offer(2);
        queue.offer(3);
        queue.printAll();

        System.out.println("add to full queue.");
        if(!queue.offer(4)){
            System.out.println("success");
            queue.printAll();
        }

        System.out.println("peek from queue.");
        if(queue.peek()==1){
            System.out.println("success");
            queue.printAll();
        }

        System.out.println("get from queue");
        if(queue.poll()==1){
            System.out.println("success");
            queue.printAll();
        }

        System.out.println("add to queue");
        queue.offer(4);
        queue.printAll();

        queue.poll();
        queue.poll();
        queue.poll();
        System.out.println("get from empty queue");
        try {
            queue.poll();
        }catch (Exception e){
            System.out.println(e.getMessage());
        }

        queue.printAll();

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值