删除链表中节点

题目:删除链表中值为val的所有节点

思路:定位到值为val的节点,将前序节点的next值指向此节点的next值

注:用了虚拟头节点,可以省去很多麻烦

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

class :
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
p = ListNode(0)
p.next = head
cur_node = p
while cur_node and cur_node.next:
if cur_node.next.val == val:
cur_node.next = cur_node.next.next
else:
cur_node = cur_node.next
return p.next

例子

1
2
3
linklist = creat_ll([1, 2, 6, 3, 4, 5, 6])
a = Solution().removeElements(linklist, 6)
print_ll(a)