美文网首页
用链表实现一个队列

用链表实现一个队列

作者: xin激流勇进 | 来源:发表于2019-04-05 15:49 被阅读0次
package structures;

public class LinkedListQueue<E> implements Queue<E> {

    private class Node {
        public E e;
        public Node next;

        public Node(E e, Node next) {
            this.e = e;
            this.next = next;
        }

        public Node(E e) {
            this(e, null);
        }

        public Node() {
            this(null, null);
        }
    }

    private Node head, tail;
    private int size;

    public LinkedListQueue() {
        head = null;
        tail = null;
        size = 0;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public E getFront() {
        if (isEmpty()) {
            throw new IllegalArgumentException("queue is empty!");
        }
        return head.e;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public void enqueue(E e) {
        if (tail == null) {
            tail = new Node(e);
            head = tail;
        } else {
            tail.next = new Node(e);
            tail = tail.next;
        }

        size ++;
    }

    @Override
    public E dequeue() {
        if (isEmpty()) {
            throw new IllegalArgumentException("queue is empty!");
        }

        Node retNode = head;
        head = head.next;
        retNode.next = null;
        if (head == null) {
            tail = null;
        }
        size --;

        return retNode.e;

    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("LinkedListQueue: front ");

        Node cur = head;
        while (cur != null) {
            stringBuilder.append(cur.e + "->");
            cur = cur.next;
        }

        stringBuilder.append(" Null tail");

        return stringBuilder.toString();
    }
}

相关文章

  • 用数组实现栈、队列

    用数组实现一个栈 用数组实现一个队列 用单链表实现给队列

  • 有关“队列”的总结

    队列 定义 分类 链式队列 (用链表实现) 静态队列 (用数组实现)图静态队列通常都必须是循环队列循环队列的讲解:...

  • c++ 实现队列

    相关资料: 用C++实现一个队列 数据结构代码实现之队列的链表实现(C/C++)

  • 队列

    一种可以实现“先进先出”的存储结构。 分类: 链式队列:用链表实现; 静态队列:用数组实现,通常都是循环队列。 循...

  • C语言第七次作业:链表

    707. 设计链表 空指针 空节点 225. 用队列实现栈 链式存储栈 双队列实现栈 232. 用栈实现队列 链式...

  • 数据结构之队列

    什么是队列 队列是一个有序列表, 可以用数组或链表实现 先入先出 使用数组模拟队列和环形队列 用数组模拟队列 思路...

  • C封装单链循环队列对象

    SingleCircularLinkedListQueue单链循环队列 单链循环队列用单向循环链表实现。 gith...

  • 用链表实现队列

    用链表实现队列,详细代码如下: 复杂度分析时间复杂度 : enqueue 和 dequeue 均为:O(1)空间复...

  • 队列

    队列的结构 队列是一种“先进先出,后进后出”的结构, 队列既可以用数组实现,也可以用链表实现,用数组实现的叫顺序队...

  • 数据结构java描述

    接口 栈 队列 集合 并查集 映射 数组 链表 栈 数组实现 链表实现 队列 数组实现 链表实现 二分搜索树 集合...

网友评论

      本文标题:用链表实现一个队列

      本文链接:https://www.haomeiwen.com/subject/lnxkiqtx.html