142. Linked List Cycle II leetcode list

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?
证明方法:http://www.tuicool.com/articles/3EZJbm

//本题的思路是首先采用两个指针分别指向链表的头节点,第一个指针一次向前走一步,第二个指针一次向前走两步,当两个指针第一次相遇时,
    //则表明链表存在环,并将当前标记的节点记为节点1,然后同时设置两个指针,指针1和指针2指针1从节点1开始遍历链表,指针2从链表头
    //开始遍历链表看,则两个指针相遇时便是链表环的入口
    ListNode *detectCycle(ListNode *head) {
        if(NULL == head || NULL == head->next)
        {
            return NULL;
        }
        else if(head->next == head)
        {
             return head;
        }

        ListNode *slow = head;
        ListNode *fast = head;
        while(fast)
        {
            fast = fast->next;//注意fast指针是一次向前走两步,但是一次向前走两步,并不能一次直接fast = fast->next->next,
            //因为fast->next有可能为空,如果不加以判断会报runtime的错误。
            if(fast)
            {
                fast = fast->next;
                slow = slow->next;
            }

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

        slow = head;
        while(slow && fast)
        {
            if(slow == fast)
            {
                return slow;
                break;
            }

            slow = slow->next;
            fast = fast->next;

        }

        return NULL;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值