in LintCode Queue ~ read.

Implement Queue by Linked List

LintCode-492.Implement Queue by Linked List

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

  1. enqueue(item). Put a new item in the queue.
  2. dequeue(). Move the first item out of the queue, return it.

This problem you need to check whether the queue is empty or not when adding a new item to the queue.

class ListNode {  
    int val;
    ListNode next;

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

public class Queue {  
    ListNode head;
    ListNode tail;

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

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

    public int dequeue() {
        if (head != null) {
            int item = head.val;
            head = head.next;

            return item;
        }

        return -1;
    }
}

Hope this helps,
Michael