题目:
思路一:
遍历链表,当结点出现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;
}
}