LeetCode OJ Linked List Cycle II

来源:互联网 发布:淘宝网店在哪里看 编辑:程序博客网 时间:2024/06/16 01:01

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?

So ingenious, from http://www.cnblogs.com/jack204/archive/2011/09/14/2175559.html

class Solution {public:    ListNode *detectCycle(ListNode *head) {        ListNode *temp_1 = head;        ListNode *temp_2 = head;        ListNode *meetPoint;        bool loop = false;        while (temp_2 != NULL && temp_2->next != NULL) {            temp_1 = temp_1->next;            temp_2 = temp_2->next->next;            if (temp_1 == temp_2) {                meetPoint = temp_1;                loop = true;                break;            }        }        if (!loop) {            return NULL;        } else {            temp_1 = head;            temp_2 = meetPoint;            while (temp_1 != temp_2) {                temp_1 = temp_1->next;                temp_2 = temp_2->next;            }            return temp_1;        }    }};


0 0
原创粉丝点击