码迷,mamicode.com
首页 > 其他好文 > 详细

142 Linked List Cycle II 环形链表 II

时间:2018-04-06 00:16:09      阅读:373      评论:0      收藏:0      [点我收藏+]

标签:开始   null   body   link   div   nod   https   highlight   不用   

给一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
说明:不应修改给定的链表。
补充:
你是否可以不用额外空间解决此题?
详见:https://leetcode.com/problems/linked-list-cycle-ii/description/

/**
 * 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==nullptr)
        {
            return nullptr;
        }
        ListNode *slow=head;
        ListNode *fast=head;
        while(fast&&fast->next)
        {
            slow=slow->next;
            fast=fast->next->next;
            if(slow==fast)
            {
                fast=head;
                while(slow!=fast)
                {
                    slow=slow->next;
                    fast=fast->next;
                }
                return slow;
            }
        }
        return nullptr;
    }
};

 

142 Linked List Cycle II 环形链表 II

标签:开始   null   body   link   div   nod   https   highlight   不用   

原文地址:https://www.cnblogs.com/xidian2014/p/8724890.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!