Remove all elements from a linked list of integers that have value val.
Example:
Input: 1->2->6->3->4->5->6, val = 6 Output: 1->2->3->4->5
Description taken from https://leetcode.com/problems/remove-linked-list-elements/.
#O(N) Time, O(1) Space
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
dummy = ListNode(0)
dummy.next = head
prev, curr = dummy, head
while curr is not None:
if curr.val == val:
prev.next = curr.next
else:
prev = curr
curr = curr.next
return dummy.next
Linked lists are built from next
reference pointers. If we want to remove a node, we can remove the reference to it within the list.
We can solve this question by traversing the linked list and if we get to a node with the value we want to remove, we will set the previous node's next
pointer to the next node of the iteration, removing the reference to the current node and removing it from the linked list.
Let's start by initializing a dummy head and setting the dummy head's next pointer to the actual head.
Then, we will set the previous pointer as the dummy head and the current pointer as the actual head.
dummy = ListNode(0)
dummy.next = head
prev, curr = dummy, head
We will then create a loop to traverse the linked list that will run while the current node hasn't reached a null value.
while curr is not None:
If the current node's value is the value we want to remove, we will set the previous node's next
pointer to the next node.
if curr.val == val:
prev.next = curr.next
Otherwise, we will move the previous pointer forward.
else:
prev = curr
At the end of each iteration, we will move the current pointer to the next node.
curr = curr.next
Once we have traversed the entire list and removed all of the unwanted nodes, we will return the list starting with the head.
return dummy.next