java實現單鏈表中是否有環的方法詳解

來源:互聯網
上載者:User

這是一道微軟經典筆試題,就是兩個指標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;
}

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.