142.环形链表 II

题目

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值