12 如果單鏈表有環,如何求出它的長度呢

2022-05-10 10:42:10 字數 2522 閱讀 6017

那怎麼求出環的長度呢?

思路:這裡面,我們需要先利用上乙個題目的hascycle方法(判斷鍊錶是否有環的那個方法),這個方法的返回值是

boolean型,但是現在要把這個方法稍做修改,讓其返回值為相遇的那個結點。然後,我們拿到這個相遇的結點就好辦了,這個結點肯定是在環裡嘛,我們可以讓

這個結點對應的指標一直往下走,直到它回到原點,就可以算出環的長度了。

方法:

//

方法:檢測單鏈表是否有環

public

node hascycle(node head)

node first =head;

node second =head;

while (second != null

) }

return

null

; }

//方法:有環鏈表中,獲取環的長度。引數node代表的是相遇的那個結點

public

intgetcyclelength(node node)

current =node;

int length = 0;

while (current != null

) }

return

length;

}

測試**:

public

class

linkcyclelength

else

}//方法過載:向鍊錶中新增結點

public

void

add(node node)

if (head == null

) else

}//方法:遍歷鍊錶(列印輸出鍊錶。方法的引數表示從節點node開始進行遍歷

public

void

print(node node)

current =node;

while (current != null

) }

class

node

public

intgetdata()

public

void setdata(int

data)

public

node getnext()

public

void

setnext(node next)

}//方法:檢測單鏈表是否有環

public

node hascycle(node head)

node first =head;

node second =head;

while (second != null

) }

return

null

; }

//方法:有環鏈表中,獲取環的長度。引數node代表的是相遇的那個結點

public

intgetcyclelength(node node)

current =node;

int length = 0;

while (current != null

) }

return

length;

}public

static

void

main(string args)

}list1.add(second);

//將尾結點指向鍊錶的第二個結點,於是單鏈表就有環了

node current1 = list1.hascycle(list1.head);//

獲取相遇的那個結點

system.out.println("環的長度為" +list1.getcyclelength(current1));

system.out.print("\r\n");

system.out.print("\r\n");

linkcyclelength list2 = new linkcyclelength(); //

向linklist中新增資料

for (int i = 0; i < 4; i++)

list2.add(list2.head);

//將頭結點新增到鍊錶當中(將尾結點指向頭結點),於是,單鏈表就有環了。備註:此時得到的這個環的結構,是本節中圖1的那種結構。

node current2=list1.hascycle(list2.head);

system.out.println("環的長度為" +list1.getcyclelength(current2)); }

}

測試結果:

環的長度為3

環的長度為4

分別是如下這種情況:

如何檢視單鏈表是否有環?

思路 就是因為有環,所以是沒有尾節點,也就是 node.next 永遠都是有值的。可以通過兩個前進速度不同的節點去迴圈,如果有相遇的時刻說明有環。private class node public node object data private node createlink node tem h...

如何判斷單鏈表裡面是否有環?

如何判斷單鏈表裡面是否有環?演算法的思想是設定兩個指標p,q,其中p每次向前移動一步,q每次向前移動兩步。那麼如果單鏈表存在環,則p和q相遇 否則q將首先遇到null。這裡主要理解乙個問題,就是為什麼當單鏈表存在環時,p和q一定會相遇呢?假定單鏈表的長度為n,並且該單鏈表是環狀的,那麼第i次迭代時,...

如何判斷單鏈表裡面是否有環?

如何判斷單鏈表裡面是否有環?演算法的思想是設定兩個指標p,q,其中p每次向前移動一步,q每次向前移動兩步。那麼如果單鏈表存在環,則p和q相遇 否則q將首先遇到null。這裡主要理解乙個問題,就是為什麼當單鏈表存在環時,p和q一定會相遇呢?假定單鏈表的長度為n,並且該單鏈表是環狀的,那麼第i次迭代時,...