leetcode142

1、Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

Follow up:
Can you solve it without using extra space?
判断一个链表有没有环常用快慢指针,之前有道题记录过,慢一步快两步,相遇就有环,遇到空指针就没有环,对于链表的环,一定是从尾节点连接到了前面某节点而成的。

寻找环开始的节点,简单推导一下~
假设环开始节点距离头节点有x个节点距离,第一次相遇节点走过了环开始节点有y个节点距离,x,y均可为0;
当第一次相遇时:
慢指针一定走了x+y,则快指针就走了2(x+y),快指针比慢指针多走了一圈,则环长一定是x+y;则慢指针再走x个节点就又回到了环开始的地方,也就是说,头节点和第一次相遇所在节点距离环开始节点相同。 第一次相遇后让头节点和慢指针一起走,相遇节点就是咯。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        if(!head) return NULL;
        ListNode* slow=head;
        ListNode* fast=head;
        while(fast&&fast->next){

            slow=slow->next;
            fast=fast->next->next;
            if(fast==slow){
                while(slow!=head){
                    slow=slow->next;
                    head=head->next;
                }
                return head;
            }
        }
        return NULL;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值