203. Remove Linked List Elements

Remove all elements from a linked list of integers that have value val.

Example:

1
2
3
> Input:  1->2->6->3->4->5->6, val = 6
> Output: 1->2->3->4->5
>

思路

pre —> 通过检验的Node

dummy —> 标记head pre, 防止head消失

Note:val相等的情况有可能连续出现,所以只有已验证 != val, 才能pre = pre.next

Note2: 如果写while pre.next, 前面要有while pre

​ 所以: while pre and pre.next

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 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
"""
pre = dummy = ListNode(-1)
dummy.next = head

while pre and pre.next:
if pre.next.val == val:
pre.next = pre.next.next
else:
pre = pre.next

return dummy.next