简体   繁体   中英

Why does my java code for reversing a linked list cause a cycle?

so I for when I run this code on leetcode, it tells me Error - Found cycle in the ListNode, but I for the life of me can't figure out why. Please help, thanks in advance!

class Solution {
public ListNode reverseList(ListNode head) {
    if (head.next == null || head == null) return head;
    
    ListNode curr = head.next;
    ListNode prev = head;
    ListNode next = head.next.next;
    
    while (curr != null) {
        curr.next = prev;
        prev = curr;
        curr = next;
        if (curr != null) next = curr.next;
    }
    
    return prev;
    
}

}

ok nevermind I know why, its because my head node needs to point to null, it was still pointing to the next element instead of null so there was a cycle between my first and second node

Let's suppose we have the following linked list:

A -> B -> C -> null

Initially, prev = A , curr = B , and next = C .

We'll trace out the first iteration of your loop:

curr.next = prev sets the link of B to A , so now our list is:

A -> B -> A -> …

The next two assignments set prev to B and curr to A .

curr != null is true. next = curr.next sets next to B .

We've lost track of the rest of the list (from C ) entirely, and the cycle will never be resolved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM