Implement Queue by Linked List 492

Question

Implement a Queue by linked list. Support the following basic methods:

enqueue(item). Put a new item in the queue.

dequeue(). Move the first item out of the queue, return it.

Example:

enqueue(1)

enqueue(2)

enqueue(3)

dequeue() # return 1

enqueue(4)

dequeue() # return 2

Solution

水题。同Implement stack 495。

代码如下:

class ListNode{
    int val;
    ListNode next;
    public ListNode(int val){
        this.val = val;
    }
}

class Queue{
    ListNode tail;
    ListNode head;

    public Queue(){
        tail = null;
        head = null;
    }

    public void enqueue(int value){
        if(head == null){
            head = new ListNode(value);
            tail = head;
        }else{
            tail.next = new ListNode(value);
            tail = tail.next;
        }
    }

    public int dequeue(){
        if(head == null){
            return -1;
        }
        int res = head.val;
        head = head.next;
        return res;
    }
}

results matching ""

    No results matching ""