queue.java

来自「Java程序设计技巧与开发实例附书源代码。」· Java 代码 · 共 60 行

JAVA
60
字号

public class Queue
{
    private Node head;
    private Node tail;
    public Queue()
    {
        head = tail = null;
    }

    public void enqueue(Object obj)
    {
        Node node = new Node(obj);
        if (head == null)
        {
            head = node;
        }
        else
        {
            tail.next = node;
        }
        tail = node;
    }

    public Object dequeue() throws QueueException
    {
        if (head == null)
        {
            throw new QueueException("removing from empty queue");
        }
        else
        {
            Object data = head.data;
            head = head.next;
            if (head == null)
            {
                tail = null;
            }
            return data;
        }
    }

    public Object peek() throws QueueException
    {
        if (head == null)
        {
            throw new QueueException("peeking into empty queue");
        }
        else
        {
            return head.data;
        }
    }

    public boolean isEmpty()
    {
        return (head == null);
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?