Why my solution using python stack doesn't work?

  • 0
    tmp = head
    stack = []
    while tmp:
    	tmp = tmp.next
    head = stack.pop()
    tmp = head
    while stack:
    	tmp.next = stack.pop()
    	tmp = tmp.next
    return head

    I am a C programmer, so I am using many rules from C to write this python code. It doesn't seem like tmp is really referencing anything...

  • 0

    You didn't change the next field of last node in the reversed list which is first node in original list.


    stack may has following nodes [ 1--> 2 -- > 3 --> None ] . You do while loop to pop up nodes and change their next field. But when stack is empty, out of the while loop, the tmp reference the 1 and it still point to 2! Just like this.

    3 --> 2 <--> 1

    You should add tmp.next = None when you out of the second while loop in your code. :)

  • 0

    Ugh.. one little thing ha. I was having the same problem so thanks for the solution though :)

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.