題目:
思路一:
遍歷鏈表,當結點出現null時,說明不是循環鏈表。
但是顯然,這是錯的
public class Solution {
public boolean hasCycle(ListNode head) {
boolean pos=true;
while(pos){
head = head.next;
if(head==null){
pos = false;
return pos;
}
}
return pos;
}
}
思路二
把經過的結點存儲在set裏面,經歷新的結點,就往set集合裏面找,如果有,就說明有環
public class Solution {
public boolean hasCycle(ListNode head) {
boolean flag = false;
Set<ListNode> Nodes = new HashSet<>();
while(head!=null){
if(Nodes.contains(head)){
flag = true;
break;
}else{
Nodes.add(head);
}
head=head.next;
}
return flag;
}
}
時間複雜度:O(n)
思路三
利用快慢節點,快結點一次走兩步,慢結點一次走一步,
- 如果慢結點等於快結點,說明有環
- 如果快結點等於null,說明沒環
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode fastNode = head;
ListNode lowNode = head;
while(fastNode!=null){
if(fastNode.next!=null){
fastNode = fastNode.next.next;
}else{
return false;
}
lowNode = lowNode.next;
if(fastNode == lowNode){
return true;
}
}
return false;
}
}