(只要把速度区分开就可以了,环形链表通过快、慢指针实现)
相交链表通过走对方的路实现
橡胶链表链接:
、添加链接描述
```c
class Solution {
public boolean hasCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while(fast!=null && fast.next!=null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
return true;
}
}
return false;
}
}
```c
class Solution {
public boolean hasCycle(ListNode head) {
ListNode slow = head;
if( head == null || head.next == null){
return false;
}
ListNode fast = head.next;
while(slow != fast){
try {
slow = slow.next;
fast = fast.next.next;
}catch (Exception e){
return false;
}
}
return true;
}
}
HashSet<ListNode> set = new HashSet<>();
while (head!=null){
if(!set.add(head)){
return true;
}
head=head.next;
}
return false;