Basics
Design
707. Design Linked List
Medium·
2 Approachesclick to switch
1
Single Linked List
O(n)
O(n)
2
Doubly Linked List
O(n)
O(n)
How to drive this playground
The playground replays a scripted sequence of MyLinkedList operations and steps through each method on the linked list. Use the operations editor to change the constructor args or the method sequence.
FIG. DESIGN LINKED LIST● INTERACTIVE
visualization loads as you reach it
- Time
- O(n)
addAtHead()is O(1) - it only rewiresself.sentinel.next.get(),addAtIndex(), anddeleteAtIndex()callgoToIndex(), which walks node by node fromself.sentineluntil it reachesindex: O(n) in the worst case.addAtTail()walkscurrent_node.nextuntil it falls off the end: O(n) in the worst case.nis the number of nodes currently in the list (self.len).- Space
- O(n)
- Each
addAtHead()/addAtTail()/addAtIndex()call allocates oneSinglyLLNode, O(1) per call, so the list itself grows to hold up tonnodes.
Reusable Code
Count Linked List Nodes
Basic·
1
Solution
O(n)
O(1)
FIG. COUNT LINKED LIST NODES● INTERACTIVE
visualization loads as you reach it
- Time
- O(n)
- The
while headloop walks every one of thennodes exactly once. - Space
- O(1)
- Only the scalar
lengthand theheadpointer are tracked, independent ofn.
Print the Elements of a Linked List
Easy·
1
Solution
O(n)
O(1)
FIG. PRINT THE ELEMENTS OF A LINKED LIST● INTERACTIVE
visualization loads as you reach it
- Time
- O(n)
nis the number of nodes - thewhile headloop advancesheadone node at a time, visiting each node once.- Space
- O(1)
- Only
headandvalueare tracked, regardless of list length.