I am writing code to answer the following LeetCode question:
Given the head of a linked list and an integer
val, remove all the nodes of the linked list that hasNode.val == val, and return the new headExample 1
Input: head = [1,2,6,3,4,5,6] val = 6 Output: [1,2,3,4,5]
This is my code:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
curr= head
dummy=ListNode(0)
prev=dummy
def skipper(prev,curr):
if curr.val == val:
curr = curr.next
else:
prev.next = curr
temp = curr
prev = temp
curr = curr.next
while prev.next:
if prev.next.val == val:
prev.next = curr
return curr
while curr:
return skipper(prev,curr)
return dummy.next
For the above code, I know that the logic works, because when I replace the inner function def skipper(prev,curr) with just while curr, and remove the while curr at the bottom of the code, then the code passes all tests.
But I want to understand how to use/call a function within a function.
The skipper function is simply meant to run through the linked list one node at a time, and 'remove' or relink the nodes so as to skip any nodes that have the same value as val.
My issue is I am not sure what to return inside the skipper function, and as a default I have returned curr- since to me this makes some sense.
But when I run the above code, I get a timeout error.
skipperdoesn't return anything