11/39
Part 2 of 7 · Pointer orderLearn and do
A dummy head gives the first node a node before it
Remove every node whose value is in a set unwanted. You delete through the predecessor, so you look one node ahead, at node.next. That works for every node but the head, which has no predecessor. So the head needs a loop of its own:
def drop_values(head, unwanted):
# the front is a special case
while head is not None and head.val in unwanted:
head = head.next
node = head
while node is not None and node.next is not None:
if node.next.val in unwanted:
node.next = node.next.next
else:
node = node.next
return head
A dummy head is an extra node in front of the head that holds no value. With it, every real node has a predecessor, and the special case is gone:
def drop_values(head, unwanted):
dummy = Node(None, head)
node = dummy
while node.next is not None:
if node.next.val in unwanted:
# stay put: the new node.next hasn't been checked
node.next = node.next.next
else:
node = node.next
return dummy.next
print(values(drop_values(linked([7, 7, 3, 7, 5]), {7})))
drop_values(7, 7, 3, 7, 5) with unwanted {7}. What's left?
Pick one to see what it prints.
Pick an answer above to see the rest