循环队列的数组实现方式与链表实现方式

假设front指向队列的头部,rear指向队列的尾部。

  • 则队列满的条件是:(rear+1)%QueueSize==front
  • 则队列为空的条件为:rear==front
  • 通用的计算队列长度的公式:(rear-front+QueueSize)%QueueSize

则队列的数组实现如下:

private int[] array;
private int front;
private int rear;

public MyQueue(int capacity){
	this.array=new int[capacity];
}
/**
*入队
*/

public void enQueue(int element)throws Exception{
	if((rear+1)%array.length==front){
		throw new Exception("队列已满");
	}
	array[rear]=element;
	rear=(rear+1)%array.length;
}

/**
*出队
*/
public int deQueue()throws Exception{
	if(rear==front){
		throw new Exception("队列已空");
	}
	int deQueueElement=array[front];
	front=(front+1)%array.length;
	return deQueueElement;
}

由于链表不用像数组那样考虑容量问题,所以我们队列的链表实现就像单链表一样,只不过它只能尾进头出而已,我们把它简称为链队列。

public class LinkQueue {
    /**
     * 结点类
     */
    class Entry{
        int data;
        Entry next;
        public Entry(){
            data=-1;
            next=null;
        }
        public Entry(int data)
        {
            this.data=data;
            this.next=null;
        }
    }

    /***定义头尾索引***/
    public  Entry front=null;
    public  Entry rear=null;
    public  int useSize=0;

    /****判断队列是否为空****/
    public boolean isEmpty(){
        return useSize==0;
    }
    /*****入队*****/
    public void enQueue(int data){
        //若此时队列为空,则直接插入,头尾索引指向该结点
        if(isEmpty()==true){
            rear=new Entry(data);
            front=rear;
        }
        else {
            //若队列不为空,则尾索引后移
            rear.next=new Entry(data);
            rear=rear.next;
        }
        useSize++;
    }

    /****出队*****/
    public int deQueue() throws Exception{
        if(isEmpty()){
            throw new Exception("队列已空");
        }
        int deQueueElement=front.data;
        front=front.next;
        useSize--;
        return deQueueElement;
    }

    /****队列遍历输出***/
    public void output(){
        Entry cur=front;
        while (cur!=null){
            System.out.println(cur.data);
            cur=cur.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
        // 动态制作一个链式队列
        LinkQueue link = new LinkQueue();
        for (int x = 0; x < 5; x++) {
            link.enQueue(x);
        }
        System.out.print("队列里的元素是:");
        link.output();
        System.out.println("队列长度是 :" + link.useSize);
        System.out.println("==================");
        try {
            link.deQueue();
        }catch (Exception e) {
            System.out.println("队列为空,不能出队");
        }
        System.out.print("执行一次出队操作后队列里的元素是:");
        link.output();
        System.out.println("执行一次出队操作后队列长度是 :" + link.useSize);

    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值