When I try to solve the leetcode 19 remove kth node from the end, I find a tricky question. I think the reason for that is I don't really understand the deep and shallow copy of python. Who can tell me why my version2 doesn't work for all test cases?
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