Java实现队列

发布于 2021-07-22  41 次阅读


一个头结点一个为指针;

Queue类代码如下:

package com.apesblog.Queue;

public class Queue<T> {
    private Node head;
    private Node last;
    private int N;

    private class Node {
        private T item;
        private Node next;

        public Node(T item, Node next) {
            this.item = item;
            this.next = next;
        }
    }

    public Queue() {
        head = new Node(null, null);
        last = null;
        N = 0;
    }

    public void enQueue(T t) {
        if (last == null) {
            last = head.next = new Node(t, null);
        } else {
            last = last.next = new Node(t, null);
        }
        N++;
    }

    public T deQueue() {
        Node p = head.next;
        if (p == null) {
            last = null;
            return null;
        }
        head.next = head.next.next;

        return p.item;
    }

}

测试类代码如下:

package com.apesblog.Queue;

public class Test {

    public static void main(String[] args) {
        Queue<String> l = new Queue<String>();
        l.enQueue("1");
        l.enQueue("2");
        l.enQueue("3");
        System.out.println(l.deQueue());
        System.out.println(l.deQueue());
        System.out.println(l.deQueue());
        System.out.println(l.deQueue());
    }

}

运行结果如下: