Sorted linked list (insert, search, delete)
Insert items one by one into their places in a sorted linked list, then search for one and delete it; only pointers change, no item moves.
A linked list is a chain of nodes, each holding a value and a pointer to the next node. Unlike an array, inserting or deleting in the middle moves no items: only two pointers change.
Read the full explanation ↓- Time:
O(n) per operation - Space:
O(n) - Horowitz–Sahni, chapter 4
- CLRS, section 10.2
42, 17, 88, 23 and 5 are inserted into the sorted list, then 23 is found and removed.
class Node:def __init__(self, val):self.val = valself.next = Nonedef sorted_list(items, target):# Insert every item into a sorted linked list, then search for target and delete it.head = Nonefor x in items:node = Node(x)if head is None or x <= head.val:node.next = headhead = nodecontinuecur = headwhile cur.next is not None and cur.next.val < x:cur = cur.nextnode.next = cur.nextcur.next = nodeprev, cur, node = None, head, Nonewhile cur is not None and cur.val < target:prev, cur = cur, cur.nextif cur is None or cur.val != target:return Falseif prev is None:head = cur.nextelse:prev.next = cur.nextreturn True
Start
headnull
Local variables
target23
Orange = changed in this step
items list
421788235
Call stack
- sorted_list()line 7
Step 1 of 62
Explanation
The idea
A linked list is a chain of nodes, each holding a value and a pointer to the next node. Unlike an array, inserting or deleting in the middle moves no items: only two pointers change.
Operations on a sorted list
- Insert: walk from the head until the next value is not smaller than
x; linkxin betweencurand its next. - Search: walk until a value not smaller than the target; since the list is sorted, you can stop before the end.
- Delete: link the node before (
prev) straight to the node after the one removed.
Cost
Finding the place costs O(n) (there is no random access), but the insert or delete itself is O(1).
What to watch in the trace
- The list is drawn from
head; the pointer names (cur,prev,node) appear under the nodes.