Question: https://leetcode.com/problems/remove-linked-list-elements/
Question Name: Remove Linked List Elements
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def removeElements(self, head, val): """ :type head: ListNode :type val: int :rtype: ListNode """ # Find the first non-val node as the new head node. newHead = head while newHead != None and newHead.val == val: newHead = newHead.next if newHead == None: return None previous = newHead current = previous.next while current != None: if current.val == val: # Skip this node. previous.next = current.next current = current.next else: # Move to the next node. previous = current current = current.next return newHead |