Wie erkenne ich einen Zyklus in einer einzig verknüpften Liste in Java?

Post a reply

Smilies
:) :( :oops: :chelo: :roll: :wink: :muza: :sorry: :angel: :read: *x) :clever:
View more smilies

BBCode is ON
[img] is ON
[flash] is OFF
[url] is ON
Smilies are ON

Topic review
   

Expand view Topic review: Wie erkenne ich einen Zyklus in einer einzig verknüpften Liste in Java?

by Guest » 20 Feb 2025, 11:45

Ich versuche festzustellen, ob eine einzeln verknüpfte Liste einen Zyklus (Schleife) in Java hat. Ich habe versucht, den Floyd -Zykluserkennungsalgorithmus (Schildkröten- und Hare -Algorithmus) zu verwenden, aber meine Implementierung funktioniert nicht richtig. < /P>
Was ist mit meiner Implementierung falsch? Hier ist mein Code: < /p>

Code: Select all

class ListNode {
int val;
ListNode next;

ListNode(int val) {
this.val = val;
this.next = null;
}
}

public class LinkedListCycleDetection {
public static boolean hasCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;

while (fast != null || fast.next != null) {
slow = slow.next;
fast = fast.next.next;

if (slow == fast) {
return true;
}
}
return false;
}

public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = head.next;

System.out.println(hasCycle(head));
}
}
Referenzen, die ich konsultiert habe:
Geeksforgeeks - Schleife in verknüpfter Liste erkennen

Top