[数据结构]-链表实现队列

本文介绍了一种使用链表来实现队列数据结构的方法。该队列包括入列、出列和获取队列中元素个数等核心操作,并提供了一个完整的Java实现示例。

[数据结构]-链表实现队列

如有问题,请指出呀。感谢。

 

 

package com.cn.jichu.day09;

public class LinkedQueue<E> {

    /**
     * 首节点
     */
    private Node head;
    /**
     * 尾节点
     */
    private Node tail;
    /**
     * 当前栈中元素个数
     */
    private int size;

    public LinkedQueue(){
        this.size = 0;
    }

    /**
     * 入列
     * @param e
     */
    public void enqueue(E e){
        Node node = new Node(e);
        if(head == null && tail == null){
            head = tail = node;
            size ++;
            return;
        }
        tail.next = node;
        tail = node;
        size ++;
    }

    /**
     * 出列
     * @return
     */
    public E dequeue(){
        if(head==null){
            throw  new IllegalArgumentException("当前队列无元素");
        }

        if(head.equals(tail)){
            System.out.println("head.equals(tail)");
            E e = head.data;
            head = tail = null;
            size --;
            return e;
        }

        E e = head.data;
        head = head.next;
        size --;
        return e;
    }

    /**
     * 获取队列中的元素个数
     * @return
     */
    public int getSize(){
        return size;
    }




    private class Node{
        private Node next;
        private E data;

        public Node(E data) {
            this.data = data;
        }
    }

    @Override
    public String toString(){
        StringBuilder ret = new StringBuilder();
        ret.append("queue  head[");
        Node node = head;
        while (node!=null){
            ret.append(node.data + "-->");
            node = node.next;
        }
        ret.append("null ] tail");
        return ret.toString();
    }

}

 

转载于:https://www.cnblogs.com/anny0404/p/10655090.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值