Given the head of a linked list and an integer val
, remove all the nodes of the linked list that have Node.val == val
, and return the new head.
head = [1,2,6,3,4,5,6]
, val = 6
Output: [1,2,3,4,5]
head = []
, val = 1
Output: []
head = [7,7,7,7]
, val = 7
Output: []
To solve this problem accurately, here are a few clarifications:
Here’s the Python implementation of the solution:
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def removeElements(head: ListNode, val: int) -> ListNode:
# Create a dummy node that helps with edge cases such as deleting the head node
dummy = ListNode(next=head)
current = dummy
# Traverse the list
while current and current.next:
if current.next.val == val:
# Remove the node by pointing to the next of next node
current.next = current.next.next
else:
current = current.next
# Return the new list head, which is the next of dummy node
return dummy.next
# Example Usage
def build_linked_list(values):
dummy = ListNode()
current = dummy
for value in values:
current.next = ListNode(val=value)
current = current.next
return dummy.next
def print_linked_list(head):
result = []
while head:
result.append(head.val)
head = head.next
print(result)
# Testing the function
head = build_linked_list([1, 2, 6, 3, 4, 5, 6])
print_linked_list(removeElements(head, 6)) # Output: [1, 2, 3, 4, 5]
current
. Every time a node with current.next.val == val
is found, remove it by pointing current.next
to current.next.next
.This should effectively solve the problem of removing elements from a linked list.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?