Design Linked List (LeetCode 707): Solution and Explanation
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
- In the constructor create a
dummynode and setsize = 0. get(index): ifindexis not in0..size-1return -1. Otherwise start atdummy.next, follownextindextimes and return that node's value.addAtIndex(index, val): ifindex > size(or negative) return. Otherwise walkprevfromdummyindextimes, setprev.next = Node(val, prev.next)and add one tosize.addAtHead(val)andaddAtTail(val)calladdAtIndex(0, val)andaddAtIndex(size, val).deleteAtIndex(index): ifindexis not in0..size-1return. Otherwise walkprevfromdummyindextimes, setprev.next = prev.next.nextand subtract one fromsize.
Step-by-step example
commands = ["MyLinkedList","addAtHead","addAtTail","addAtIndex","get","deleteAtIndex","get"], values = [[],[1],[3],[1,2],[1],[1],[1]]
MyLinkedList()creates the dummy node. The list is dummy -> null and size = 0.addAtHead(1)isaddAtIndex(0, 1): prev stays on the dummy, so 1 is linked right after it.addAtTail(3)isaddAtIndex(1, 3): prev walks to 1 and 3 goes after it. List: 1 -> 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.get(1): cur starts at 1 and moves once to 2, so it returns 2.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 -= 11class MyLinkedList {
2 private static class LinkNode {
3 int val;
4 LinkNode next;
5 LinkNode(int val, LinkNode next) {
6 this.val = val;
7 this.next = next;
8 }
9 }
10
11 private final LinkNode dummy;
12 private int size;
13
14 public MyLinkedList() {
15 dummy = new LinkNode(0, null);
16 size = 0;
17 }
18
19 public int get(int index) {
20 if (index < 0 || index >= size) {
21 return -1;
22 }
23 LinkNode cur = dummy.next;
24 for (int i = 0; i < index; i++) {
25 cur = cur.next;
26 }
27 return cur.val;
28 }
29
30 public void addAtHead(int val) {
31 addAtIndex(0, val);
32 }
33
34 public void addAtTail(int val) {
35 addAtIndex(size, val);
36 }
37
38 public void addAtIndex(int index, int val) {
39 if (index < 0 || index > size) {
40 return;
41 }
42 LinkNode prev = dummy;
43 for (int i = 0; i < index; i++) {
44 prev = prev.next;
45 }
46 prev.next = new LinkNode(val, prev.next);
47 size++;
48 }
49
50 public void deleteAtIndex(int index) {
51 if (index < 0 || index >= size) {
52 return;
53 }
54 LinkNode prev = dummy;
55 for (int i = 0; i < index; i++) {
56 prev = prev.next;
57 }
58 prev.next = prev.next.next;
59 size--;
60 }
61}1class MyLinkedList {
2 struct LinkNode {
3 int val;
4 LinkNode* next;
5 LinkNode(int v, LinkNode* n) : val(v), next(n) {}
6 };
7
8 LinkNode* dummy;
9 int size;
10
11public:
12 MyLinkedList() {
13 dummy = new LinkNode(0, nullptr);
14 size = 0;
15 }
16
17 int get(int index) {
18 if (index < 0 || index >= size) {
19 return -1;
20 }
21 LinkNode* cur = dummy->next;
22 for (int i = 0; i < index; i++) {
23 cur = cur->next;
24 }
25 return cur->val;
26 }
27
28 void addAtHead(int val) {
29 addAtIndex(0, val);
30 }
31
32 void addAtTail(int val) {
33 addAtIndex(size, val);
34 }
35
36 void addAtIndex(int index, int val) {
37 if (index < 0 || index > size) {
38 return;
39 }
40 LinkNode* prev = dummy;
41 for (int i = 0; i < index; i++) {
42 prev = prev->next;
43 }
44 prev->next = new LinkNode(val, prev->next);
45 size++;
46 }
47
48 void deleteAtIndex(int index) {
49 if (index < 0 || index >= size) {
50 return;
51 }
52 LinkNode* prev = dummy;
53 for (int i = 0; i < index; i++) {
54 prev = prev->next;
55 }
56 LinkNode* gone = prev->next;
57 prev->next = gone->next;
58 delete gone;
59 size--;
60 }
61};Time and space complexity
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.
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.