java数据结构——链表实现队列

java数据结构——链表实现队列

package fwb.COllection;

/**
 * @author :yixing
 * @Have a nice day!
 * @date : 2022/5/6
 * @time :  16:28
 */

public class Queue<T> {

    class Node{
        T val;
        Node next;
        public Node(T val,Node next){
            this.val = val;
            this.next = next;
        }
        Node(T val){
            this(val,null);
        }
    }

    //记录首结点(初值为null)
    private Node head = null;
    //记录最后一个结点(初值为null)
    private Node tail = null;
    //记录队列中元素的个数
    int size = 0;
    public boolean isEmpty(){
        return size == 0;
    }
    public int size(){
        return size;
    }

    //入队
    public void enqueue(T var){
        Node node = new Node(var);
        if(tail ==null){
            head = node;
        }else{
            tail.next = node;
        }
        tail = node;
        size++;

    }
    //出队
    public T dequeue(){
        if(isEmpty()){
            throw new RuntimeException("队列为空");
        }
        Node oldHead = head;
        head = head.next;
        if(head == null){
            tail =null;
        }
        size--;
        return oldHead.val;

    }

    //队顶元素
    public T peek(){
        if(isEmpty()){
            throw new RuntimeException("队列空");
        }
        return head.val;
    }

    //输出元素
    public void show(){
        Node p = head;
        while(p!=null){
            System.out.println(p.val);
            p = p.next;
        }
    }
    public static void main(String[] args) {
        Queue<Integer> queue = new Queue<>();
        queue.enqueue(1);
        queue.enqueue(2);
        queue.enqueue(3);
        System.out.println("元素个数:"+queue.size());
        queue.show();

        System.out.println("队头元素:"+queue.peek());

        int result = queue.dequeue();
        System.out.println("出队元素:"+result);

        System.out.println("出队后队头元素:"+queue.peek());

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值