2.5-找链表环的起点(same in LeetCode)

来源:互联网 发布:矩阵奇异值分解过程 编辑:程序博客网 时间:2024/06/11 01:53

Given a circular linked list, implement an algorithm which returns node at the beginning of the loop.
DEFINITION
Circular linked list: A (corrupt) linked list in which a node’s next pointer points to an earlier node, so as to make a loop in the linked list.
EXAMPLE
Input: A -> B -> C -> D -> E -> C [the same C as earlier]
Output: C


leetcode:Linked List Cycle II

http://blog.csdn.net/todorovchen/article/details/24052849

ListNode *detectCycle(ListNode *head){    if(head==NULL)        return NULL;    ListNode *slow = head, *fast = head;    while(fast != NULL && fast->next != NULL)    {        slow = slow->next;        fast = fast->next->next;        if(slow == fast)// first meet        {            slow=head;            while(slow != fast)            {                slow = slow->next;                fast = fast->next;            }            return slow;// second meet        }    }    return NULL;}


0 0
原创粉丝点击