CathyQian
CathyQian

Reputation: 1159

Why does my reverse linked list only return head?

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

Upvotes: 0

Views: 432

Answers (1)

Harish
Harish

Reputation: 368

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.

Upvotes: 1

Related Questions