0

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

enter image description here

Ryan
  • 33
  • 5
  • I have already read that question, but I don't think that is helpful for me – Ryan Jan 12 '17 at 20:38
  • Then you need to clarify the question, and explain what specifically is still confusing you. Don't just say "doesn't work", say what you expect the result to be, why you expect it, and what you're getting instead. – Barmar Jan 12 '17 at 20:44
  • you can see the pic I add, I think my question is quite clear if you really read it – Ryan Jan 12 '17 at 20:50
  • When you remove the first node in a linked list, you change the value of `dummy` to point to the second node, but `head` still points to the original first node. – Barmar Jan 12 '17 at 20:54
  • This has nothing to do with shallow vs. deep copies, since you never copied anything. – Barmar Jan 12 '17 at 20:54

0 Answers0