【发布时间】:2021-05-29 17:17:21
【问题描述】:
我正在尝试使用辅助递归函数解决“从具有值 val 的整数的链接列表中删除所有元素”问题,但它不起作用。
Example:
Input: 1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5
我的解决方案:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def checkHead(self, head, val):
if head.val == val and head.next:
head = head.next
self.checkhead(head,val)
elif head.val and not head.next:
head = None
return head
def removeElements(self, head: ListNode, val: int) -> ListNode:
if not head:
return head
head = self.checkHead(head, val)
if not head:
return head
curr = head
while curr and curr.next:
if curr.next.val == val:
curr.next = curr.next.next
curr = curr.next
return None
失败的测试用例:
Input: 1->1, val = 1
Output: []
当我将递归checkHead 函数的值返回为head = self.checkHead(head, val) 时,它指出head 等于“1”但是当我调试它时,我可以看到程序从checkHead 返回为None .我想知道问题出在哪里。
【问题讨论】:
-
行“elif head.val and not head.next:”是可疑的。你错过了 == 吗?
-
正如@Stefan 所说,
elif的elif语句中可能需要head.val == valcheckHead。
标签: python recursion data-structures linked-list singly-linked-list