解法一、构建新的链表
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
if head is None:
return head
else:
p=ListNode()
q=p
while head:
if head.val == val:
head=head.next
else:
q.next=head
q=head
head=head.next
q.next=None
return p.next
解法二、递归
def removeElements(self, head, val):
if head is None:
return head
head.next = self.removeElements(head.next, val)
if head.val == val:
return head.next
else:
return head
第一个返回值出现时(即到末尾head.next... = none),递归返回上一层
第一次未理解卡在最后一个null返回后,不知道返回上一层