Implement queue using Linkedlist

Pattern: Implementation

easy

Keep head and tail pointers. Push links a new node after the tail; pop removes the head. When the last node leaves, set tail to null as well, or the next push links onto a dead node.

The problem

Build a class LinkedListQueue with push(x) (add at the back), pop() (remove and return the front), peek() and isEmpty(), using linked nodes.

On an empty structure, pop, top and peek return -1. This is this guide's own rule; the linked page does not say what happens.

Think first

  • Which end should be the front so that removing is O(1)?
  • How do you add at the back in O(1)?
  • What must happen to tail when the queue empties?

Hints

    Brute force, and why it fails

    With only a head pointer, every push walks to the end: O(n).

    The key insight

    A second pointer to the tail makes adding at the back O(1), and removing at the head is already O(1).

    Dry run

    list5
    head5
    tail5

    Empty: head and tail are null. push(5) makes 5 both ends.

    Step 1 of 4

    The plan

    push(x): node = Node(x)
             if tail is null: head = tail = node
             else: tail.next = node; tail = node
    pop():   if head is null: return -1
             x = head.val; head = head.next
             if head is null: tail = null
             return x
    

    Complexity

    Time
    O(1) per operation
    Space
    O(n)

    Each operation changes at most two pointers.

    Edge cases

    • Pop until empty, then push again: this is where a stale tail breaks.
    • Pop on an empty queue: -1.
    I've built my logic, show the code

    Java

    class LinkedListQueue {
        private static class Node {
            int val;
            Node next;
            Node(int val) { this.val = val; }
        }
    
        private Node head = null, tail = null;      // remove at the head, add at the tail
    
        public void push(int x) {
            Node node = new Node(x);
            if (tail == null) head = tail = node;   // the first item is both ends
            else { tail.next = node; tail = node; }
        }
    
        public int pop() {
            if (head == null) return -1;            // this guide's rule for an empty queue
            int x = head.val;
            head = head.next;
            if (head == null) tail = null;          // the queue became empty
            return x;
        }
    
        public int peek() {
            return head == null ? -1 : head.val;
        }
    
        public boolean isEmpty() {
            return head == null;
        }
    }

    C++

    class LinkedListQueue {
    public:
        struct Node {
            int val;
            Node* next;
            Node(int v) : val(v), next(NULL) {}
        };
    
        Node* head = NULL;                          // remove at the head
        Node* tail = NULL;                          // add at the tail
    
        void push(int x) {
            Node* node = new Node(x);
            if (tail == NULL) head = tail = node;   // the first item is both ends
            else { tail->next = node; tail = node; }
        }
    
        int pop() {
            if (head == NULL) return -1;            // this guide's rule for an empty queue
            Node* old = head;
            int x = old->val;
            head = old->next;
            if (head == NULL) tail = NULL;          // the queue became empty
            delete old;
            return x;
        }
    
        int peek() {
            return head == NULL ? -1 : head->val;
        }
    
        bool isEmpty() {
            return head == NULL;
        }
    };

    Python

    from lib import ListNode
    
    
    class LinkedListQueue:
        def __init__(self):
            self.head = self.tail = None            # remove at the head, add at the tail
    
        def push(self, x: int) -> None:
            node = ListNode(x)
            if self.tail is None:
                self.head = self.tail = node        # the first item is both ends
            else:
                self.tail.next = node
                self.tail = node
    
        def pop(self) -> int:
            if self.head is None:
                return -1                           # this guide's rule for an empty queue
            x = self.head.val
            self.head = self.head.next
            if self.head is None:
                self.tail = None                    # the queue became empty
            return x
    
        def peek(self) -> int:
            return -1 if self.head is None else self.head.val
    
        def isEmpty(self) -> bool:
            return self.head is None

    Common mistakes

    • Forgetting to clear tail when the last node leaves.
    • Adding at the head and removing at the tail, which needs the node before the tail.

    Similar problems