Java实现一个队列(链表)

本文介绍了如何使用Java编程语言实现一个基于链表的队列数据结构,并提供了相关的代码及测试用例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

- 代码

class Node{
    //创建一个链表
    int val;
    Node next;
    Node (int val, Node next) {
        this.val=val;
        this.next=next;
    }// end Node
    Node (int val){
        this (val,null);
    }
}// end class Node
public class Queue {
    //利用链表实现一个队列
    private Node head=null;
    private Node tail=null;
    //记录链表长度
    private int size=0;
    //队列三种核心操作:入队列offer,出队列pop,取队顶元素peek.
    //入队列
    public void offer(int i){
        Node node=new Node(i);
        //如果队列为空,则head=node
        if (tail==null){
            head=node;
        }else{
            //队列不为空
            tail.next=node;
        }
        tail=node;
        size++;
    }//end offer
    //出队列
    public int poll(){
       if(head==tail){
           return Integer.parseInt( null );
       }//end if
        //利用oldhead的记录出队列元素
        Node oldhead=head;
        head=head.next;
        //如果出队列结点为队列中最后一个元素,将tail也置空
        if(head==null){
            tail=null;
        }
        size--;
        return oldhead.val;
    }//end poll
    //取队列首元素
    public int peek(){
        if(head==tail){
            return Integer.parseInt( null );
        }
        Node oldhead=head;
        return oldhead.val;
    }//end peek
    public int size(){
        return size;
    }
    public static void main(String[] args) {
        Queue Offer=new Queue();
        Offer.offer(1);
        Offer.offer(2);
        Offer.offer(3);
        System.out.println(Offer.size());
        System.out.println(Offer.poll());
    }
}// end class Queue

- 代码测试用例:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值