Linked List Cycle II

来源:互联网 发布:mac sierra是什么 编辑:程序博客网 时间:2024/05/21 12:45
<pre name="code" class="cpp">/** * 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* h1 = head, *h2 = head;         //h1走一步,h2走两步,两个值必定会相遇         while(NULL != h1 && NULL != h2)         {             h1 = h1->next;             h2 = h2->next;             if(h2 == NULL)                return NULL;            h2 = h2->next;                        if(h1 == h2)//如果相遇,则表示有环。            {                h1 = head;                                while(h1 != NULL && h2 != NULL)//一个从头走,一个从之前相遇的位置走,则必定会在第一个相交点遇见。                {                        if(h1 == h2)//说明head就是第一个相遇点                    {                        return h1;                    }                    h1 = h1->next;                    h2 = h2->next;                }                                break;            }         }         return NULL;    }};


                                             
0 0
原创粉丝点击