Design Linked List

Implement MyLinkedList, a 0-indexed singly linked list, without using a built-in list type. Support get(index), addAtHead(val), addAtTail(val), addAtIndex(index, val) and deleteAtIndex(index). get returns -1 for an invalid index; addAtIndex does nothing when index is greater than the length, and appends when it equals the length; deleteAtIndex does nothing for an invalid index.

30:00

Design Linked List
medium
Free written solution
Topics
Companies

Implement MyLinkedList, a 0-indexed singly linked list, without using a built-in list type. Support get(index), addAtHead(val), addAtTail(val), addAtIndex(index, val) and deleteAtIndex(index). get returns -1 for an invalid index; addAtIndex does nothing when index is greater than the length, and appends when it equals the length; deleteAtIndex does nothing for an invalid index.

Example 1:
Input: {"commands":["MyLinkedList","addAtHead","addAtTail","addAtIndex","get","deleteAtIndex","get"],"values":[[],[1],[3],[1,2],[1],[1],[1]]}
Output: [null,null,null,null,2,null,3]
Constraints:
  • 0≤index,val≤10000 \leq \text{index}, \text{val} \leq 1000

  • Do not use the built-in LinkedList library.

  • At most 20002000 calls will be made to get, addAtHead, addAtTail, addAtIndex and deleteAtIndex.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"commands":["MyLinkedList","addAtHead","addAtTail","addAtIndex","get","deleteAtIndex","get"],"values":[[],[1],[3],[1,2],[1],[1],[1]]}

MyLinkedList() creates a dummy node that sits before index 0, so every insert and delete has a node in front of it. size = 0.

Calls

new

()

→ null

addAtHead

(1)

addAtTail

(3)

addAtIndex

(1,2)

get

(1)

deleteAtIndex

(1)

get

(1)

MyLinkedList()

size = 0

.
dummy
head

→

null

yellow = cur / prev pointer

green = node just linked in

dummy = sentinel before index 0

Variables
VariableValue
callMyLinkedList()
size0
output[null]
DepthFunction Call
Stack empty
0/20