Design Linked List (LeetCode 707): Solution and Explanation

Medium
Linked List
Design

Build a 0-indexed linked list class with get, addAtHead, addAtTail, addAtIndex and deleteAtIndex, without a built-in list type.

Intuition

Every operation is about one position in the list, and in a singly linked list you can only change a link from the node in front of it. So inserts and deletes at index i both need a pointer parked on node i - 1.

Index 0 has no node in front of it, which normally forces special cases for the head. A dummy node placed before index 0 fixes that: walking i steps from the dummy always lands on the node before position i, even when i is 0.

Keeping a size counter makes the validity rules cheap. get and deleteAtIndex accept 0 <= index < size, addAtIndex accepts 0 <= index <= size, and addAtHead and addAtTail become addAtIndex(0, val) and addAtIndex(size, val).

Approach: Singly linked list with a dummy head

  1. In the constructor create a dummy node and set size = 0.
  2. get(index): if index is not in 0..size-1 return -1. Otherwise start at dummy.next, follow next index times and return that node's value.
  3. addAtIndex(index, val): if index > size (or negative) return. Otherwise walk prev from dummy index times, set prev.next = Node(val, prev.next) and add one to size.
  4. addAtHead(val) and addAtTail(val) call addAtIndex(0, val) and addAtIndex(size, val).
  5. deleteAtIndex(index): if index is not in 0..size-1 return. Otherwise walk prev from dummy index times, set prev.next = prev.next.next and subtract one from size.

Step-by-step example

commands = ["MyLinkedList","addAtHead","addAtTail","addAtIndex","get","deleteAtIndex","get"], values = [[],[1],[3],[1,2],[1],[1],[1]]
  1. MyLinkedList() creates the dummy node. The list is dummy -> null and size = 0.
  2. addAtHead(1) is addAtIndex(0, 1): prev stays on the dummy, so 1 is linked right after it. addAtTail(3) is addAtIndex(1, 3): prev walks to 1 and 3 goes after it. List: 1 -> 3.
  3. addAtIndex(1, 2): prev walks one step to node 1, the new node 2 points to 3, and 1 points to 2. List: 1 -> 2 -> 3, size 3.
  4. get(1): cur starts at 1 and moves once to 2, so it returns 2.
  5. deleteAtIndex(1): prev walks to 1 and sets 1.next = 3, unlinking 2. get(1) now returns 3. Output: [null,null,null,null,2,null,3].

Code: Python, Java, C++

1class LinkNode:
2    def __init__(self, val=0, next=None):
3        self.val = val
4        self.next = next
5
6
7class MyLinkedList:
8    def __init__(self):
9        self.dummy = LinkNode()
10        self.size = 0
11
12    def get(self, index: int) -> int:
13        if index < 0 or index >= self.size:
14            return -1
15        cur = self.dummy.next
16        for _ in range(index):
17            cur = cur.next
18        return cur.val
19
20    def addAtHead(self, val: int) -> None:
21        self.addAtIndex(0, val)
22
23    def addAtTail(self, val: int) -> None:
24        self.addAtIndex(self.size, val)
25
26    def addAtIndex(self, index: int, val: int) -> None:
27        if index < 0 or index > self.size:
28            return
29        prev = self.dummy
30        for _ in range(index):
31            prev = prev.next
32        prev.next = LinkNode(val, prev.next)
33        self.size += 1
34
35    def deleteAtIndex(self, index: int) -> None:
36        if index < 0 or index >= self.size:
37            return
38        prev = self.dummy
39        for _ in range(index):
40            prev = prev.next
41        prev.next = prev.next.next
42        self.size -= 1
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(index) per call

get, addAtIndex and deleteAtIndex walk at most index nodes. addAtHead is O(1); addAtTail walks the whole list, O(n), unless you also keep a tail pointer.

Space

O(n)

One node per stored value plus the dummy; each call uses O(1) extra space.

Other approaches

Doubly linked list with head and tail sentinels (time O(min(index, n - index)) per call, space O(n))

Keep both prev and next pointers and two sentinels. Walk from whichever end is closer to the index, which halves the worst-case walk and makes addAtTail O(1).

Singly linked list without a dummy (time O(index) per call, space O(n))

Store only a head pointer. It works, but inserting or deleting at index 0 needs its own branch because there is no node in front of the head.

Common mistakes

  • Using index >= size as the reject test in addAtIndex. Inserting at index == size is valid and means append.
  • Walking prev index - 1 steps from the first real node instead of index steps from the dummy, which breaks at index 0.
  • Forgetting to update size on a successful insert or delete, or updating it when the call was rejected.
  • Naming the node class Node or ListNode in an environment that already defines one; any distinct name works.

Frequently asked questions

Why use a dummy node at all?

It gives index 0 a predecessor. Every insert and delete then has the same shape, prev.next = ..., with no separate head-update branch.

Does addAtIndex accept index equal to the size?

Yes. It appends the node at the end, which is exactly what addAtTail does. Only index greater than the size is ignored.

Singly or doubly linked?

Either passes. Singly linked is shorter to write; doubly linked lets you walk from the tail for indexes near the end and makes addAtTail constant time.