AAlgoLoopSpaced repetition for LeetCode
MEDIUMLinked ListLeetCode ↗

Design Linked List

The key idea

Use a sentinel (dummy) head node so every operation — insert at head, insert in the middle, delete — is handled by the same walk-to-prev logic with no special case for the first node. To insert or delete at position index, walk to the node just before it, then splice.

Problem

Design your implementation of a singly linked list. A node in a singly linked list should have two attributes: val and next. val is the value of the current node, and next is a pointer/reference to the next node. If you want to use a doubly linked list, you will need one more attribute prev to indicate the previous node in the list. Assume all nodes in the list are 0-indexed.

Implement the MyLinkedList class:

- MyLinkedList() initializes the MyLinkedList object.
- get(index) returns the value of the index-th node in the linked list. If the index is invalid, returns -1.
- addAtHead(val) adds a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
- addAtTail(val) appends a node of value val as the last element of the linked list.
- addAtIndex(index, val) adds a node of value val before the index-th node in the linked list. If index equals the length of the list, the node will be appended to the end. If index is greater than the length, the node will not be inserted.
- deleteAtIndex(index) deletes the index-th node in the linked list, if the index is valid.

Constraints

Examples

Input: ["MyLinkedList","addAtHead","addAtTail","addAtIndex","get","deleteAtIndex","get"] [[],[1],[3],[1,2],[1],[1],[1]] Output: [null,null,null,null,2,null,3]
Input: ["MyLinkedList","addAtHead","addAtHead","addAtIndex","deleteAtIndex","get"] [[],[7],[2],[1,5],[1],[1]] Output: [null,null,null,null,null,7]

Complexity

Time: O(index) Space: O(1)

See the full solution

410310
Step-by-step visualization
Start free →

More Linked List problems