Design Linked List
The key idea
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
0 <= index, val <= 1000- Please do not use the built-in LinkedList library.
- At most
2000calls will be made toget,addAtHead,addAtTail,addAtIndex, anddeleteAtIndex.
Examples
Complexity
Time: O(index) Space: O(1)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Linked List problems
- Add Two NumbersMEDIUM
- Copy List with Random PointerMEDIUM
- Insert Greatest Common Divisors in Linked ListMEDIUM
- Intersection of Two Linked ListsEASY
- Maximum Twin Sum of a Linked ListMEDIUM
- Merge Two Sorted ListsEASY
- Odd Even Linked ListMEDIUM
- Partition ListMEDIUM
- Remove Duplicates from Sorted List IIMEDIUM
- Remove Linked List ElementsEASY
- Remove Nth Node From End of ListMEDIUM
- Reorder ListMEDIUM