[C语言][LeetCode][142]Linked List Cycle II

题目

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?

标签

Linked List、Two Pointers

难度

中等

分析

题目意思是如果链表里面有回环,找出回环开始的位置,如果没有,返回null。我的做法是先判断链表是否有回环,判断回环的方法可以参照下文
http://blog.csdn.net/Timsley/article/details/51155365
如果找到回环,快指针指回表头,然后快慢指针继续走,快慢指针每次都是走一步,如果相遇,就找到这个指针,返回即可。

C代码实现

struct ListNode *detectCycle(struct ListNode *head) 
{
    struct ListNode *fast, *slow;
    bool fgHasCycle = false;

    if(!head)
        return NULL;

    fast = head;
    slow = head;

    while(fast && fast->next)
    {
        fast = fast->next->next;
        slow = slow->next;

        if(fast == slow)
        {
            fgHasCycle = true;
            break;
        }
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值