删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
# 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
"""
#创建一个空指针,指向head,意在能操作head的第一个node
node = ListNode(None)
node.next = head
#nodelist等于node的引用,用来操作遍历每个node节点
nodelist = node
while nodelist.next:
if nodelist.next.val == val:
nodelist.next = nodelist.next.next
else:
nodelist = nodelist.next
#返回node.next,即操作后的head
return node.next
网友评论