0
votes

I was doing the reverse a linked list leetcode problem: Reverse a singly linked list. However my code only returns the head although I think the head is linked with its next node by:

pre = curr.next  

Below is my code. I'm having difficulty figuring out where the problem is. Any help is appreciated!!

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head == None:
            return head

        pre, curr, post = None, head, head.next
        while post:
            pre = curr.next
            pre, curr, post = curr, post, post.next

        pre = curr.next

        return curr
1
You aren't building a new, reversed, list; you are just walking the original list to the end. - chepner
I think your line pre = curr.next is maybe the wrong way. Try curr.next = pre instead? - Hitobat

1 Answers

1
votes

In linkedlist the nodes are connected using the next variable(given in leetcode). What you are doing is just simply moving forward without reversing the relation between them.

What you should be doing is

class Solution(object):
def reverseList(self, head):
    """
    :type head: ListNode
    :rtype: ListNode
    """
    if head == None:
        return head

    pre, curr, post = None, head, head.next
    while post:
        curr.next=pre
        pre, curr, post = curr, post, post.next
    curr.next=pre

    return curr

I hope you could see where you went wrong. A handtrace of the code will always be helpful to understand the logic.