Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
A chain holds 1, 2, 3, 4. Show, by following the links, what remove(head, 1) and remove(head, 3) do, and what happens for a value that is not in the chain.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, compare your working with the solution.
Plan. The head is a special case. For another node, find the node before it and skip over it.
remove(head, 1): the head holds 1, so the new head is head.next, the node with 2. The chain is 2, 3, 4.remove(head, 3) on 1, 2, 3, 4: walk to the node before the 3, which is the 2. Make 2.next skip the 3 and point to the 4. The chain is 1, 2, 4.current.next is None), and nothing changes. The chain is returned as it was.Answer: [1, 2, 4]. Removing 1 gives 2, 3, 4, and removing a missing value changes nothing.
Log in to join the discussion.
Loading…