LeetCode141 Linked List Cycle. LeetCode142 Linked List Cycle II

链表相关题

141. Linked List Cycle

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space? (Easy)

 

分析:

采用快慢指针,一个走两步,一个走一步,快得能追上慢的说明有环,走到nullptr还没有相遇说明没有环。

代码:

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     bool hasCycle(ListNode *head) {
12         if (head == NULL) {
13             return 0;
14         }
15         ListNode* slow = head;
16         ListNode* fast = head;
17         while (fast != nullptr && fast->next != nullptr) {
18             slow = slow->next;
19             fast = fast->next->next;
20             if (slow == fast) {
21                 return true;
22             }
23         }
24         return false;
25     }
26 };

 

142. Linked List Cycle II

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?(Medium)

 

分析:

1)同linked-list-cycle-i一题,使用快慢指针方法,判定是否存在环,并记录两指针相遇位置(Z);
2)将两指针分别放在链表头(X)和相遇位置(Z),并改为相同速度推进,则两指针在环开始位置相遇(Y)。
 
证明如下:
如下图所示,X,Y,Z分别为链表起始位置,环开始位置和两指针相遇位置,则根据快指针速度为慢指针速度的两倍,可以得出:
2*(a + b) = a + b + n * (b + c);即
a=(n - 1) * b + n * c = (n - 1)(b + c) +c;
注意到b+c恰好为环的长度,故可以推出,如将此时两指针分别放在起始位置和相遇位置,并以相同速度前进,当一个指针走完距离a时,另一个指针恰好走出 绕环n-1圈加上c的距离。
故两指针会在环开始位置相遇。
 
代码:
 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *detectCycle(ListNode *head) {
12         if(head == nullptr) {
13             return 0;
14         }
15         ListNode* slow = head;
16         ListNode* fast = head;
17         while (fast != nullptr && fast->next != nullptr) {
18             slow = slow -> next;
19             fast = fast -> next -> next;
20             if(slow == fast){
21                 break;
22             }
23         }
24         if (fast == nullptr || fast->next == nullptr) {
25             return nullptr;
26         }
27         slow = head;
28         while (slow != fast) {
29             slow = slow->next;
30             fast = fast->next;
31         }
32         return slow;
33     }
34 };

 

 
 
 

转载于:https://www.cnblogs.com/wangxiaobao/p/6188596.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值