141、142 Linked List Cycle & II
2016-09-11 22:32
323 查看
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?
思路
非常简单的一道题,如果链表有环,则在遍历的时候永远不会结束,一直在环内转圈。
所以,设置快慢指针,如果相遇,则说明有环。
代码(C++)
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.
思路
在上一题的基础上,slow和fast相遇后,slow和head同时出发,每次一个步长,相遇的时候就是交点。
代码(C++)
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
思路
非常简单的一道题,如果链表有环,则在遍历的时候永远不会结束,一直在环内转圈。
所以,设置快慢指针,如果相遇,则说明有环。
代码(C++)
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: bool hasCycle(ListNode *head) { if (NULL == head || NULL == head->next) return false; ListNode* slow = head; ListNode* fast = head; while (fast->next && fast->next->next) { slow = slow->next; fast = fast->next->next; if (slow == fast) return true; } return false; } };
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.
思路
在上一题的基础上,slow和fast相遇后,slow和head同时出发,每次一个步长,相遇的时候就是交点。
代码(C++)
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *detectCycle(ListNode *head) { if (NULL == head || NULL == head->next) return false; ListNode* slow = head; ListNode* fast = head; while (fast->next && fast->next->next) { slow = slow->next; fast = fast->next->next; if (slow == fast) { ListNode* tmp = head; while (tmp != slow) { tmp = tmp->next; slow = slow->next; } return tmp; } } return NULL; } };
相关文章推荐
- Leetcode 141/142 (链表题) Linked List Cycle && Linked List Cycle II
- <LeetCode OJ> 141 / 142 Linked List Cycle(I / II)
- [Leetcode 141 & 142, medium] Linked List Cycle (I and II)
- leetcode-141&142 Linked List Cycle I & II
- leetcode-141-142 Linked List Cycle I II
- [leetcode] 141& 142 Linked List Cycle I& II
- LeetCode.142(141) Linked List Cycle && Linked List Cycle (II)
- leetcode[141&142]:Linked List Cycle I & II
- Leetcode 142: Linked List Cycle II & Leetcode 287: Find the Duplicate Number
- Easy 141题 Linked List Cycle Medium 142题 Linked List Cycle II
- leetcode 141.Linked List Cycle && 142 .Linked List Cycle ii
- [leetc 4000 ode141 142]Linked List Cycle I II
- LeetCode141 Linked List Cycle. LeetCode142 Linked List Cycle II
- LeetCode(141)(142) Linked List Cycle I II
- LeetCode 141 Linked List Cycle和142 Linked List Cycle II
- leetcode[142]Linked List Cycle II
- [Leetcode][JAVA] Linked List Cycle I && II
- leetcode-Linked List Cycle I & II
- [LeetCode]142 Linked List Cycle II
- LeetCode:Linked List Cycle && Linked List Cycle II