LeetCode 142. Linked List Cycle II

来源:互联网 发布:冒泡排序的算法思想 编辑:程序博客网 时间:2024/05/03 06:55

Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.

Note: Do not modify the linked list.

Thousands of articles to introduce this idea. This is really very neat.

    ListNode *detectCycle(ListNode *head) {        if(!head) return NULL;        ListNode* slow = head;        ListNode* fast = head;        while(fast && fast->next && fast->next->next) {            slow = slow->next;            fast = fast->next->next;            if(slow == fast) {                break;            }        }        if(!fast || !fast->next || !fast->next->next) return NULL; // remember to check the no circle condition.        slow = head;        while(slow != fast) {            slow = slow->next;            fast = fast->next;        }        return slow;    }


0 0
原创粉丝点击