队列的链式存储结构

由于链队列采用链式结构来保存队列中的所有元素,该队列允许添加无限多个数据元素,因此链队列无队列满的问题。

package MyJava2;

public class LinkQueue {
    class Node{
        private String data;
        private Node next;
        public Node(){}
        public Node(String data,Node next){
            this.data=data;
            this.next=next;
        }
    }
    private Node front;
    private Node rear;
    private int size=0;
    public LinkQueue(){
        front=null;
        rear=null;
    }
    public LinkQueue(String data){
        front=new Node(data,null);
        rear=front;
        size++;
    }
    public int len(){
        return size;
    }

    public void add(String data){
        if(front==null){
            front=new Node(data,null);
            rear=front;
        }else {
            Node newNode=new Node(data,null);
            rear.next=newNode;
            rear=newNode;
        }size++;
    }

    public String remove(){//移除队首元素
        Node oldNode=front;
        front=oldNode.next;
        oldNode.next=null;
        size--;
        return oldNode.data;
    }

    public String getRear(){//返回队尾元素
        return rear.data;
    }
    public void clear(){
        front=null;
        rear=null;
        size=0;
    }
    public String toString(){
        StringBuffer sb=new StringBuffer();
        Node current=front;
        for(;current!=null;current=current.next){
            sb.append(current.data.toString()+",");
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        LinkQueue queue=new LinkQueue("1");
        queue.add("2");
        queue.add("3");
        System.out.println(queue.len());
        System.out.println(queue.remove());
        System.out.println(queue.getRear());
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Dream答案

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值