当我尝试解决leetcode 19从最后删除第k个节点时,我发现了一个棘手的问题。我认为原因是我不太了解python的深层和浅层副本。谁能告诉我为什么我的版本2对所有测试用例都不起作用?
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n): //this is correct
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
help=[]
dummy=ListNode(None)
dummy.next=head
cur=dummy
while cur:
help.append(cur)
cur=cur.next
node=help[-n-1]
node.next=node.next.next
return dummy.next
def removeNthFromEnd2(self, head, n): //this is not correct when test case is head [1], n=1
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
help=[]
dummy=ListNode(None)
dummy.next=head
while dummy:
help.append(dummy)
dummy=dummy.next
node=help[-n-1]
node.next=node.next.next
return head