Leetcode 142. Linked List Cycle II

来源:互联网 发布:淘宝卖家关闭花呗支付 编辑:程序博客网 时间:2024/05/29 05:17

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?

s思路:
1. 如何用快慢指针大法检测cycle,在Leetcode 141. Linked List Cycle以及说清楚了。不说了,直接来!

//方法1:快慢指针移动大法!class Solution {public:    ListNode *detectCycle(ListNode *head) {        //        if(!head) return NULL;        ListNode* fast=head->next,*slow=head;        while(fast&&fast!=slow){            fast=fast->next?fast->next->next:NULL;            slow=slow->next;        }        if(fast==NULL) return NULL;        fast=head;        slow=slow->next;//这里有一个bug:把fast放在头部,那么slow需要往下移动一位,才开始同步移动!        while(fast!=slow){            fast=fast->next;            slow=slow->next;        }        return fast;    }};
0 0
原创粉丝点击