You are given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.
Example 1:
Input: head = [2,1,4,1,2,3], val = 2
Output: [1,4,1,3]Example 2:
Input: head = [1,1], val = 1
Output: []Constraints:
0 <= Length of the list <= 10,000.1 <= Node.val <= 500 <= val <= 50# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
arr = []
cur = head
while cur:
if cur.val != val:
arr.append(cur.val)
cur = cur.next
if not arr:
return None
res = ListNode(arr[0])
cur = res
for i in range(1, len(arr)):
node = ListNode(arr[i])
cur.next = node
cur = cur.next
return res# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
if not head:
return None
head.next = self.removeElements(head.next, val)
return head if head.val != val else head.next# Definition for singly-linked list.
# 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:
dummy = ListNode(0, head)
prev, curr = dummy, head
while curr:
nxt = curr.next
if curr.val == val:
prev.next = nxt
else:
prev = curr
curr = nxt
return dummy.next# Definition for singly-linked list.
# 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:
dummy = ListNode(-1, head)
curr = dummy
while curr.next:
if curr.next.val == val:
curr.next = curr.next.next
else:
curr = curr.next
return dummy.next