142-Linked-List-Cycle-II
0x0 题目详情
0x1 解题思路
0x2 代码实现
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head==null || head.next==null || head.next.next==null){
return null;
}
ListNode fast=head.next.next;
ListNode slow=head.next;
//第一次相遇
while(fast!=slow){
if(fast.next==null || fast.next.next==null){
return null;
}
fast=fast.next.next;
slow=slow.next;
}
// if(fast==null){
// return null;
// }
fast=head;
//第二次相遇
while(fast!=slow){
fast=fast.next;
slow=slow.next;
}
return slow;
}
}0x3 课后总结
Last updated