赞
踩
203. Remove Linked List Elements
1.这样可以处理空链表特殊情况,头指针为要删除的值的特殊情况
使用空指针p在这里的好处在于,
1.p保存了头结点,
2.而最开始pre和p指向了同一个节点对象,这样如果首节点是空节点或等于val时,可以直接进行操作,因此首节点也可以当做普通节点来处理,返回值是p.next即可,这种解法的巧妙之处就在这里。
class Solution:
def removeElements(self, head, val):
dummyNode = ListNode(0)
dummyNode.next = head
pre = dummyNode
cur = head
while cur:
if cur.val==val:
pre.next = cur.next
else:
pre = cur
cur = cur.next
return dummyNode.next
class Solution: def removeElements(self, head, val): if not head: return None while head!=None and head.val==val: head = head.next pre = None cur = head while cur: if cur.val==val: pre.next = cur.next else: pre = cur cur = cur.next return head
class Solution: def removeElements(self, head, val): """ :type head: ListNode :type val: int :rtype: ListNode """ while head and head.val==val: head=head.next p = head while p and p.next: if p.next.val == val: p.next = p.next.next else: p = p.next return head
class Solution:
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
if not head: return None
head.next = self.removeElements(head.next, val)
return head.next if head.val==val else head
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。