【51】Linked List Cycle II

 

题目链接: Linked List Cycle II

题目意思: 给定一个链表,如果链表有环求出环的起点,否则返回NULL

解题思路: 

    1. 判断链表是否有环: 两个指针,一个一次走一步,一个一次走两步,如果指针相遇说明有环,否则无环。

    2. 如果有环的情况下,我们可以画个图(图片来自网络)

        

         假设两个指针在z点相遇。则

         a. 指针1走过路程为a + b;指针2走过的路程为 a+b+c+b

         b. 因为指针2的速度是指针1的两倍,则有2(a+b) = a+b+c+b => a = c

         c. 因此,当两个指针在z点相遇之后,可以让指针1指向链表起点x,然后两个指针每次分别都走一步

             当两个指针再次相遇的时候,即为环的起点,即Y点

 

代码:

 


/**
 * 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);
};

ListNode* Solution::detectCycle(ListNode *head) {
    if (NULL == head) {
        return NULL;
    }
    ListNode *tmpHeadOne = head;
    ListNode *tmpHeadTwo = head;
    int step = 0;
    bool isCycle = false;
    while ((tmpHeadOne != NULL) && (tmpHeadTwo != NULL)) {
        if ((step != 0) && (tmpHeadOne == tmpHeadTwo)) {
            isCycle = true;
            break;
        }
        step++;
        tmpHeadOne = tmpHeadOne->next;
        tmpHeadTwo = tmpHeadTwo->next;
        if (tmpHeadTwo != NULL) {
            tmpHeadTwo = tmpHeadTwo->next;
        }
    } 
    if (!isCycle) {
        return NULL; 
    }
    tmpHeadOne = head;
    while (tmpHeadOne != tmpHeadTwo) {
        tmpHeadOne = tmpHeadOne->next;
        tmpHeadTwo = tmpHeadTwo->next;
    }
    return tmpHeadOne;
}

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值