问题
Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.
Follow up:
Can you solve it without using extra space?
思路:
1)、判断是否为循环链表,是则继续,否则返回null,
利用快慢方法,利用 slow 和 fast ,slow 往前走一步,fast往前走两步,如果最后出现slow==fast,两者相遇,证明为循环链表
2)有环的情况下, 求链表的入环节点
* slow再次从头出发,每次走一步,
* meetNode从相遇点出发,每次走一步,
* 再次相遇即为环入口点。
* 注:此方法在牛客BAT算法课链表的部分有讲解
/**
* 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) {
return null;
}
ListNode slow=head;
ListNode fast=head;
ListNode meetNode = head;
while(fast.next!=null&&fast.next.next!=null){
slow = slow.next;
fast = fast.next.next;
if (slow==fast) {
meetNode=slow;
break;
}
}
if(fast.next==null||fast.next.next==null){
return null;
}
//slow从开头开始和meetNode逐个增加,与meetNode相遇时则为循环入口
slow=head;
while (slow!=meetNode) {
slow = slow.next;
meetNode = meetNode.next;
}
return meetNode;
}
}