侧边栏壁纸
博主头像
小顺

一帆风顺 ⛵️⛵️⛵️

  • 累计撰写 70 篇文章
  • 累计创建 0 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

Java实现队列

小顺
2021-07-22 / 0 评论 / 0 点赞 / 28 阅读 / 181 字

一个头结点一个为指针;

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

}
0

评论区