题目
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
Note: Do not modify the linked list.
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.
分析
- 判断环形链表环开始的位置,首先让快指针移动一个环的长度,然后慢指针开始移动,当快指针和慢指针相遇的时候所在的节点就是环开始的位置
- 这种思想和19.删除链表的倒数第n个节点的思想一样
代码和注释
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *detectCycle(struct ListNode *head) {
struct ListNode *p = head, *q = head; //没有使用虚拟头节点,p,q直接指向head.因此头节点为空的特殊情况要单独讨论
if (p == NULL) return p;
do {
p = p->next;
q = q->next;
if (q == NULL || q->next == NULL) return NULL; // 快指针如果指向null,说明没有环
q = q->next;
} while(p != q); //运行到这里说明p和q相等
int cnt = 0;
do {
cnt++;
p = p->next;
} while(p != q); //p继续移动,q保持不变,当p和q再次相等的时候,刚好走了一个环的长度
p = head, q = head; //重新初始化p,q指向头节点
while(cnt--) p = p->next; //快指针先走一个环的长度,慢指针再开始走,当快慢指针相遇的节点就是环开始的节点
while(p != q){
p = p->next;
q = q->next;
}
return p;
}