1

I'm getting a loop in linked list error while trying to reverse a linked list-

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        
        first = head
        second = head.next
        third = head.next.next
        
        while third != None and third.next != None:
            
            third = second.next
            
            second.next = first
            first = second
            second = third

            
        print(first)
        print (second)
            
        return second
        

Output : [5]

And the error is-

Error - Found cycle in the ListNode ListNode{val: 5, next: None}

1
  • Any idea how to debug this issue? Commented Jul 26, 2020 at 23:34

1 Answer 1

1

If you look closely at:

third = second.next

'third' value does not ever change

How is the reversed list supposed to be?

Usually in a reversed Linked List the head becomes the tail, and vice versa and the next values point to the previous link

Sign up to request clarification or add additional context in comments.

2 Comments

yes, it's not changing... can you please modify the code in the while block?
You can find a python algorithm to reverse a LinkedList here geeksforgeeks.org/reverse-a-linked-list

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.