首页 > 学院 > 开发设计 > 正文

Leetcode 142. Linked List Cycle II

2019-11-11 06:35:35
字体:
来源:转载
供稿:网友

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; }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表