【java版数据结构】链式队列的设计与实现

队列是一种特殊的数据结构,就像在食堂排队打饭一般,它具有先进先出的特点,队列可用数组或者链表实现,这里我们选择用链表实现对列,由于java具有面向对象的特点,我们通过创建一个Queue的类来秒速队列,在Queue类内部创建一个Node类来描述队列存储的每一个结点。

队列的成员变量和方法

成员变量方法
Node head 头结点Queue()构造方法
int N 队列元素个数isEmpty()判断队列是否是空的
Node class{}内部结点类size()返回队列元素个数
enQueue(T item)入队操作
deQueue()出队操作
重写iterator()遍历方法

结点类的实现

private class Node{
	T item;
	Node next;
	public Node(T item,Node next){
		this.item=item;
		this.next=next;
}
}

队列的构造方法

//构造方法
    public  Queue(){
        this.head=new Node(null,null);
        this.last=null;
        this.N=0;

    }

判断队列是否是空的

//判断队列是否是空的
    public boolean isEmpty(){
        return  N==0;
    }

返回队列元素个数

//返回队列元素个数
    public  int size(){
        return N;
    }

入队

//入队
    public void enQueue(T item){
        //判断链表是否是空的,如果是,则没有尾结点,就将新结点插入到头结点之后,并将其作尾结点
        if (isEmpty()){
           last =new Node(item,null);
           head.next=last;
        }
        else{
            //找到旧的尾结点
            Node oldLast=last;
            //创建新结点,并将新结点作为新的尾结点
            last=new Node(item,null);
            //让旧尾结点指向新尾结点
            oldLast.next=last;
        }
        //元素个数加一
        N++;
    }

出队

 //出队
    public  T deQueue(){
        //如果队列是空的,就返回空
        if (isEmpty()){
            return null;
        }
        //找到头结点的下一个结点
        Node curr=head.next;
        //让头结点的下一个结点变为下一个结点的下一个结点(删除操作)
        head.next=curr.next;
        //元素个数减一
        N--;
        //出完一个元素后,队列全部出队,则last尾结点需要置空
        if (isEmpty()){
            last=null;
        }
        return  curr.item;
    }

遍历队列

    //遍历队列

    @Override
    public Iterator<T> iterator() {
        return new QIterator();
    }
    //内部类实现Iterator接口
    private  class QIterator implements Iterator{
        private Node n;

        public QIterator() {
            this.n = head;
        }

        @Override
        public boolean hasNext() {
            return n.next!=null;
        }

        @Override
        public Object next() {
            n=n.next;
            return n.item;
        }
    }
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值