地址:点击打开链接
删除链表中为给定的值的元素的节点
注意判断条件
答案:
# 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
"""
while head and head.val == val:
head = head.next
if not head :
return head
p = head
q = head.next
while q:
if q.val == val:
q = q.next
else: #下面主要是考虑到1,6,6,1这种情况
p.next = q
p = p.next
q = q.next
p.next = q #考虑到1,2这种情况
return head