在時間復雜度為O(n)、空間復雜度為O(1)的情況下,檢測單向鏈表中是否存在環。
可以類比于操場跑步。假設兩個人A、B在操場上跑步,A的速度是10,B的速度是20,兩人同時從起點出發,會在起點再次相遇。利用這一點可證,用兩個指針以不同的速度向后移動,如果存在環,它們一定會相遇,且滿足時間復雜度和空間復雜度要求。
實現代碼如下
//Node Class
package LinkList;
public class Node {
public int val;
public Node next;
public Node() {
// TODO Auto-generated constructor stub
this.val = new Integer(-1);
this.next = null;
}
}
//main
import LinkList.Node;
public class Main {
public boolean hasRing(Node head) {
Node fast,slow;
fast = slow = head;
while (head.next!=null) {
fast = fast.next.next;
slow = slow.next;
if (fast==slow) {
return true;
}
}
return false;
}
public static void main(String[] args) {
Node node[];
node = new Node[10];
for (int i = 0; i < node.length; i++) {
node[i] = new Node();
}
for(int i=0;i<9;i++){
node[i].val = i;
node[i].next = node[i+1];
}
node[9].next = node[7];
node[9].val = 9;
for (int i = 0; i < node.length; i++) {
System.out.println(node[i].val + ":" + node[i].next.val);
}
boolean hasRing = new Main().hasRing(node[0]);
System.out.println("是否存在環"+":"+hasRing);
}
}