LeetCode 142. Linked List Cycle II

来源:互联网 发布:天津中年同志软件 编辑:程序博客网 时间:2024/06/15 12:55

142. Linked List Cycle II

Description
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?

Analysis
这道题的意思就是判断链表中是否存在着环,如果存在则返回环则返回环的起点。
这道的要点在于它不仅要判断是否是环,还要返回环的起点。
我对这道题的解法是判断是否是环再找起点。
判断是否是环比较简单,利用两个指针一个跳一步,一个跳两步,如果有重合,则说明存在环。
而找到起点,则比较技巧了。
假设环程度为len,second走到环的起点长度为m,则first走的长度为2m,而假设second从环起点走到相遇点的的长度为n,则此时first走了2n。
则可得到len = 2m+2n-m-n = m+n,而现在first已经在环中走了长度n,还需要m才能走到环起点。而second走到环起点的长度为m。
所以可以利用一个从头开始的指针,跟first一起一次跳一步,当这两个相遇后就是环起点。

Code

/** * 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 head ;        //if(head->next == NULL) return head;        ListNode * first = head;        ListNode * second = head;        int res = 0;        while(first!=NULL&&first->next!=NULL){                      second = second->next;            first = first->next->next;            if(first == second){                //break;                //res=1;                ListNode * ans = head;                while(1){                    if(ans == first) return first;                    else{                        ans= ans->next;                        first = first->next;                    }                }            }        }        return NULL;        //if(res==0) return NULL;    }};
0 0