我有以下實現,檢查鏈表是否有循環。如果是,則返回true,否則返回false。如何檢查鏈表是否在Java中有循環?
看起來代碼是正確的,但即使它有一個循環它仍然返回false。我錯過了什麼?謝謝
import java.util.*;
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
class LinkedListCycle {
boolean hasCycle(ListNode head) {
if(head == null) {
return false;
}
ListNode walker = head;
ListNode runner = head;
while(runner.next!=null && runner.next.next!=null) {
walker = walker.next;
runner = runner.next.next;
if(walker==runner) return true;
}
return false;
}
public static void main(String args[]) {
LinkedListCycle llc = new LinkedListCycle();
ListNode ln = new ListNode(1);
ln.next = new ListNode(2);
ln.next.next = new ListNode(3);
ln.next.next.next = new ListNode(4);
ln.next.next.next.next = new ListNode(2);
ln.next.next.next.next.next = new ListNode(1);
System.out.println(llc.hasCycle(ln));
}
}
你最好發佈的情況下,當存在循環,並返回false。 –