description:
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
Solution:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
#first remove leading val
while head:
if head.val == val:
head = head.next
else:
break
rethead = head
if rethead:
temp = head.next
else:
temp = None
#remove between or last
while temp:
if temp.val == val:
head.next = temp.next
temp = temp.next
else:
head = head.next
temp = temp.next
return rethead