這是一道微軟經典筆試題,就是兩個指針h1,h2都從頭開始遍歷單鏈表,h1每次向前走1步,h2每次向前走2步,如果h2碰到了NULL,說明環不存在;如果h2碰到本應在身後的h1說明環存在(也就是發生了套圈)。
如果環不存在,一定是h2先碰到NULL:
如果環存在,h2與h1一定會相遇,而且相遇的點在環內:h2比h1遍歷的速度快,一定不會在開始的那段非環的鏈表部分相遇,所以當h1,h2都進入環後,h2每次移動都會使h2與h1之間在前進方向上的差距縮小1,最後,會使得h1和h2差距減少為0,也即相遇
代碼如下:
package org.myorg;
public class Test{
public static boolean isExsitLoop(SingleList a) {
Node<T> slow = a.head;
Node<T> fast = a.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[]){
SingleList list = new SingleList();
for(int i=0;i<100;i++){
list.add(i);
}
System.out.print(SingleList.isExistingLoop(list));
}
}
代碼如下:
package org.myorg;
public class Node{
public Object data; //節點存儲的數據對象
public Node next; //指向下一個節點的引用
public Node(Object value){
this.data = value;
}
public Node(){
this.data = null;
this.next = null;
}
}
代碼如下:
package org.myorg;
public class SingleList{
private int size;
private Node head;
private void init(){
this.size = 0;
this.head = new Node();
}
public SingleList(){
init();
}
public boolean contains(Object value){
boolean flag = false;
Node p = head.next;
while(p!=null){
if(value.equals(p.data)){
flag = true;
break;
}else(
p = p.next;
)
}
return flag;
}
public boolean add(Object value){
if(contains(value))
return false;
else{
Node p = new Node(value);
p.next=head.next;
head.next = p;
size++;
}
return true;
}
}