LeetCode141 Linked List Cycle. LeetCode142 Linked List Cycle II
Posted wangxiaobao的博客
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 /** 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 };
以上是关于LeetCode141 Linked List Cycle. LeetCode142 Linked List Cycle II的主要内容,如果未能解决你的问题,请参考以下文章
leetcode 141. Linked List Cycle
leetcode-141. Linked List Cycle
LeetCode 141. Linked List Cycle
[Leetcode]141. Linked List Cycle