【LeetCode】Linked List Cycle II
2014-08-28 00:00
357 查看
Given a linked list, return the node where the cycle begins. If there is no cycle, return
Follow up:
Can you solve it without using extra space?
思路:
首先利用快慢指针判断是否存在循环(快慢指针是否会相遇),如果存在,那么第一个循环开始的节点一定位于head和快慢指针相遇节点之间。寻找方法就是设置一个指针p从头部节点开始,沿着链表移动,再让另外一个指针绕着cycle不断转圈,如果移动过程中碰到p,则p就是循环开始的第一个节点,如果饶了一圈还没有碰到,就让p移到下一个节点,知道相遇。
null.
Follow up:
Can you solve it without using extra space?
思路:
首先利用快慢指针判断是否存在循环(快慢指针是否会相遇),如果存在,那么第一个循环开始的节点一定位于head和快慢指针相遇节点之间。寻找方法就是设置一个指针p从头部节点开始,沿着链表移动,再让另外一个指针绕着cycle不断转圈,如果移动过程中碰到p,则p就是循环开始的第一个节点,如果饶了一圈还没有碰到,就让p移到下一个节点,知道相遇。
class Solution { public: ListNode *detectCycle(ListNode *head) { if (head == NULL) { return NULL; } ListNode *slow, *fast; slow = fast = head; do { fast = fast->next ? fast->next->next : fast->next; slow = slow->next; }while (fast != NULL && fast != slow); if (fast == NULL) { // no cycle return NULL; } while (fast != head) { if ((fast = fast->next) == slow) { head = head->next; } } return fast; } };
相关文章推荐
- LeetCode:Linked List Cycle II
- LeetCode:Linked List Cycle II
- LeetCode | Linked List Cycle II
- LeetCode | Linked List Cycle II
- LeetCode之Linked List Cycle II
- leetcode - Linked List Cycle II
- [Leetcode 141 & 142, medium] Linked List Cycle (I and II)
- [LeetCode] - Linked List Cycle II
- [leetcode]Linked List Cycle II
- LeetCode: Linked List Cycle II
- [算法][LeetCode]Linked List Cycle & Linked List Cycle II——单链表中的环
- [LeetCode] Linked List Cycle II
- Leetcode: Linked List Cycle II
- [LeetCode]Linked List Cycle II
- [leetcode]Linked List Cycle II
- Leetcode Linked List Cycle II
- leetcode: Linked List Cycle II
- Leetcode: Linked List Cycle II
- LeetCode - Linked List Cycle II
- leetcode Linked List Cycle II