Leetcode: Remove element from list
head of a linked list, remove all items with
val. Afterwards, return the new head.
To solve this problem, we need to consider three cases. The element can be in the beginning, in the middle or at the end. For the middle case, we can just define
el.next = el.next.next. This also works for the end, except that we need to make sure that the
next element is not
None. The beginning is a little bit more difficult. Here we can work around this problem by adding a pseudo-node in front of the beginning and then always look at the
next one. At the end we return
new_head.next. The other corner case is if two nodes that need to be deleted are right next to each other. In this case we cannot move the pointer forward.
Runtime: 169 ms, faster than 5.14% of Python3 online submissions for Remove Linked List Elements. Memory Usage: 17.8 MB, less than 81.69% of Python3 online submissions for Remove Linked List Elements.