请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

dummyHead 和 dummyTail 就不需要做那么多判断了

回答1 浏览121 2020-10-09 19:55:02

使用 dummyHead 和 dummyTail,就不需要那么多判断了,直接如下就好了

 @Override
    public void enqueue(E e) {
        dummyTail.next = new Node(e);
        dummyTail = dummyTail.next; 
        size++;
    }

    @Override
    public E dequeue() {
        Node curr = dummyHead.next;
        dummyHead.next = curr.next;
        curr.next = null;
        size--;
        return curr.e;
    }

话不多说,代码奉上

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);
        }

        @Override
        public String toString() {
            return e.toString();
        }
    }

    private Node dummyHead;
    private Node dummyTail;
    private int size;

    public LinkedListQueue() {
        dummyHead = dummyTail = new Node(null, null);
        size = 0;
    }

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

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

    @Override
    public void enqueue(E e) {
        dummyTail.next = new Node(e);
        dummyTail = dummyTail.next;
        size++;
    }

    @Override
    public E dequeue() {
        Node curr = dummyHead.next;
        dummyHead.next = curr.next;
        curr.next = null;
        size--;
        return curr.e;
    }

    @Override
    public E getFront() {
        Node curr = dummyHead.next;
        return curr.e;
    }

    @Override
    public String toString() {
        StringBuilder res = new StringBuilder();
        res.append("Queue: front ");
        Node curr = dummyHead.next;
        while (curr != null) {
            res.append(curr + "->");
            curr = curr.next;
        }
        res.append("NULL tail");
        return res.toString();
    }

    public static void main(String[] args) {
        LinkedListQueue<Integer> queue = new LinkedListQueue<>();
        for(int i = 0; i < 10; i++) {
            queue.enqueue(i);
            System.out.println(queue);

            if (i % 3 == 2) {
                queue.dequeue();
                System.out.println(queue);
            }
        }

    }
}

添加回答

1回答

玩转数据结构

难度中级
时长25小时
人数6220
好评度100%

体系完整,细致入微,0基础入门:动态数组/栈/队列/链表/BST/堆/线段树/Trie/并查集/AVL/红黑树…

讲师

liuyubobobo 全栈工程师

创业者,全栈工程师,持续学习者。对技术开发,产品设计、前后端,ios,html5,智能算法等领域均有接触;拥有多款独立App作品;对一切可编程的东西有浓厚兴趣,对游戏编程格外感兴趣。相信编程改变一切。

意见反馈 帮助中心 APP下载
官方微信