LeetCode Linked List Cycle II

来源:互联网 发布:数据分析培训班哪个好 编辑:程序博客网 时间:2024/05/10 01:46

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?

struct ListNode {    int val;    ListNode *next;    ListNode(int x) : val(x), next(NULL) {} }; class Solution {public: ListNode *detectCycle(ListNode *head) {        bool flag = false;        ListNode *fast, *slow;    fast = slow = head;    while(fast && fast->next) {    fast = fast->next->next;    slow = slow->next;    if(fast == slow) {    flag = true;    break;    }    }    if(!flag) return NULL;    int count = 1;// count表示环的长度     fast = fast->next->next;    slow = slow->next;    //当fast与slow重合后,还需count-1次才能重新重合     while(fast != slow) {    fast = fast->next->next;    slow = slow->next;    count++;    }    fast = slow = head;    while(count--) fast = fast->next;while(fast != slow) {fast = fast->next;slow = slow->next;}return fast;       }};


0 0
原创粉丝点击