LeetCode 142. Linked List Cycle II

来源:互联网 发布:mac炉石传说无法运行 编辑:程序博客网 时间:2024/05/17 07:54

描述

找到环的起始节点

解决

若存在环,则从头节点和相遇点每次走一步,一定会在起始点处相遇。


/** * 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)            return false;        ListNode *t1 = head, *t2 = head;        while (t2 -> next && t2 -> next -> next)        {            t1 = t1 -> next;            t2 = t2 -> next -> next;            if (t1 == t2)            {                t2 = head;                while (t1 != t2)                {                    t1 = t1 -> next;                    t2 = t2 -> next;                }                return t1;            }        }        return NULL;    }};
0 0
原创粉丝点击