Linked List Cycle II

原创 2016年05月31日 14:26:16
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?

思路:找到一个有环链表的起始节点。定义两个指针,一个指针每次走一步,一个指针每次走两步。这样,当两者相遇的时候说明整个链表含有环。当两者第一次相遇的时候,快指针走的路径是慢指针的两倍。可以得出从第一次相遇的地方到链表环起始节点的距离和从链表head开始到循环起始节点的距离是相等的。这样,再遍历一次链表即可。

/**
 * 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 *slow=head;
        ListNode *fast=head;
        while(true)
        {
            if(fast==NULL || fast->next==NULL)
                return NULL;
            slow=slow->next;
            fast=fast->next->next;
            if(slow==fast)
                break;
        }
        //跳出循环说明有环
        slow=head;
        while(slow!=fast)
        {
            slow=slow->next;
            fast=fast->next;
        }
        return slow;
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

【LeetCode】Linked List Cycle II

参考链接 http://www.cnblogs.com/x1957/p/3406448.html 题目描述 Linked List Cycle II   Give...

Linked List Cycle I&&II

Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without usin...

leetcode:Linked List Cycle II

COPY FROM: 比I麻烦点的就是找到循环开始点TAT I只是判断是否循环。要求不使用额外空间(不然hash就可以了 按I的思路,我们又慢指针S和快指针F。。。F走两...

[LeedCode]Find the Duplicate Number/Linked List Cycle II

看到别人一个时间复杂度为O(n)的解法,觉得很有意思。记录一下。题目: Given an array nums containing n + 1 integers where each intege...

【LeetCode】Linked List Cycle II

题目 Given a linked list, return the node where the cycle begins. If there is no cycle, return nu...

[leetcode] 142. Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null. Not...

LeetCode 142 Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null. N...

[leetcode] 142. Linked List Cycle II 解题报告

题目链接:https://leetcode.com/problems/linked-list-cycle-ii/ Given a linked list, return the node wher...

[LeetCode] Linked List Cycle II, Solution

Given a linked list, return the node where the cycle begins. If there is no cycle, return null. Fol...

【LeetCode】linked-list-cycle-ii

题干Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull. Fo...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Linked List Cycle II
举报原因:
原因补充:

(最多只允许输入30个字)