# 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
"""
if not head:
return head
if not head.next:
if head.val == val:
return None
else:
return head
dummy = ListNode(0)
dummy.next = head
pre = dummy
p = head
while p:
if p.val == val:
pre.next = p.next
p = p.next
else:
pre = p
p = p.next
return dummy.next
有一种很天才的做法,递归法:
class Solution(object):
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)
if head.val == val:
return head.next
else:
return head
网友评论