使用链表实现队列

队列的特点:先进先出

使用链表实现队列非常简单,成员变量只需要定义一个链表节点。先进去的数据放在链表的头部,后进去的数据依次放在链表尾部。每次出队列的时候只需要把头部的数据获取就可以了,然后node.next=node.next.next,删除原先的链表节点。

代码如下:




public class LinkQueue {

    private Node front;
    private int size;
    public LinkQueue(){
        this.front = new Node(0);
    }

    public void push(int val){
        Node newNode = new Node(val);
        Node temp = front;
        while (temp.next!=null){
            temp=temp.next;
        }
        temp.next=newNode;
        size++;
    }

    public int poll(){
        if (front.next==null){
            throw new RuntimeException("队列已空");
        }
        Node firstNode = front.next;
        front.next=front.next.next;
        size--;
        return firstNode.data;
    }

    public void traverse(){
        Node temp = front.next;
        while (temp!=null){
            System.out.print(temp.data+"\t");
            temp=temp.next;
        }
    }

    public int size(){
        return size;
    }

    static class Node{
        public int data;
        public Node next;
        public Node(int data){
            this.data = data;
        }
    }

    public static void main(String[] args) {
        //数据测试
        LinkQueue linkQueue = new LinkQueue();
        linkQueue.push(1);
        linkQueue.push(2);
        linkQueue.push(3);
        linkQueue.push(4);
        linkQueue.push(5);
        System.out.println("linkQueue.size = " + linkQueue.size);
        linkQueue.traverse();
        System.out.println("linkQueue.poll() = " + linkQueue.poll());
        System.out.println("linkQueue.poll() = " + linkQueue.poll());
        System.out.println("linkQueue.poll() = " + linkQueue.poll());
        System.out.println("linkQueue.poll() = " + linkQueue.poll());
        System.out.println("linkQueue.poll() = " + linkQueue.poll());
        System.out.println("linkQueue.poll() = " + linkQueue.poll());
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值