[leetcode][list][two pointers] Linked List Cycle II

来源:互联网 发布:matlab数据采集工具箱 编辑:程序博客网 时间:2024/05/21 08:55

题目:

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?

/** * 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(NULL == head || NULL == head->next) return NULL;        ListNode *slow = head;        ListNode *fast = head->next;        while(fast && fast->next && slow != fast){            slow = slow->next;            fast = fast->next->next;        }        if(slow != fast) return NULL;//无环        //计算环中元素个数n        int cnt = 1;        slow = slow->next;        while(slow != fast){            ++cnt;            slow = slow->next;        }        //前后指针,一个指针先走n部,然后两个指针同步向前,相遇点就是入口        ListNode *front = head;        ListNode *behind = head;        for(int i = 0; i < cnt; ++i) front = front->next;        while(front != behind){            front = front->next;            behind = behind->next;        }        return front;    }};


0 0
原创粉丝点击