您的位置:首页 > 其它

Leetcode: Linked List Cycle II

2013-12-18 23:49 357 查看
Given a linked list, return the node where the cycle begins. If there is no cycle, return 
null
.

Follow up:

Can you solve it without using extra space?

对应方式1 - 快慢指针

/**

 * 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 == NULL) {

            return NULL;

        }

        

        ListNode *slow = head;

        ListNode *fast = head->next;

        while (fast != NULL && fast->next != NULL && fast != slow) {

            slow = slow->next;

            fast = fast->next->next;

        }

        

        // No cycle

        if (fast == NULL || fast->next == NULL) {

            return NULL;

        }

        

        // Has cycle

        slow = head;

        fast = fast->next;

        while (slow != fast) {

            slow = slow->next;

            fast = fast->next;

        }

        

        return slow;

    }

};

链表转置貌似找不到环的起点。

======================第二次======================

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

return NULL;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: