Leetcode 链表 Linked List Cycle II
2014-08-30 23:04
369 查看
本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie
Total Accepted: 20444 Total
Submissions: 66195My Submissions
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?
题意:给定一个单链表,判断该链表中是否存在环,如果存在,返回环开始的节点
思路:
1.定义两个指针,快指针fast每次走两步,慢指针s每次走一次,如果它们在非尾结点处相遇,则说明存在环
2.若存在环,设环的周长为r,相遇时,慢指针走了 slow步,快指针走了 2s步,快指针在环内已经走了 n环,
则有等式 2s = s + nr 既而有 s = nr
3.在相遇的时候,另设一个每次走一步的慢指针slow2从链表开头往前走。因为 s = nr,所以两个慢指针会在环的开始点相遇
复杂度:时间O(n)
Linked List Cycle II
Total Accepted: 20444 TotalSubmissions: 66195My Submissions
Given a linked list, return the node where the cycle begins. If there is no cycle, return
null.
Follow up:
Can you solve it without using extra space?
题意:给定一个单链表,判断该链表中是否存在环,如果存在,返回环开始的节点
思路:
1.定义两个指针,快指针fast每次走两步,慢指针s每次走一次,如果它们在非尾结点处相遇,则说明存在环
2.若存在环,设环的周长为r,相遇时,慢指针走了 slow步,快指针走了 2s步,快指针在环内已经走了 n环,
则有等式 2s = s + nr 既而有 s = nr
3.在相遇的时候,另设一个每次走一步的慢指针slow2从链表开头往前走。因为 s = nr,所以两个慢指针会在环的开始点相遇
复杂度:时间O(n)
struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; ListNode *detectCycle(ListNode *head) { if(!head || !head->next) return NULL; ListNode *fast, *slow, *slow2; fast = slow = slow2 = head; while(fast && fast->next){ fast = fast->next->next; slow = slow->next; if(fast == slow && fast != NULL){ while(slow->next){ if(slow == slow2){ return slow; } slow = slow->next; slow2 = slow2->next; } } } return NULL; }
相关文章推荐
- 【LeetCode-面试算法经典-Java实现】【142-Linked List Cycle II(单链表中有环II)】
- [LeetCode] Linked List Cycle II 链表环起始位置
- leetcode_c++:链表:Linked List Cycle II(142)
- 链表-leetcode 142 Linked List Cycle II
- Linked List Cycle leetcode II java (寻找链表环的入口)
- [LeetCode]Linked List Cycle & Linked List Cycle II——单链表中的环
- 【leetcode】【单链表】【142】Linked List Cycle II
- LeetCode刷题笔记(链表):linked-list-cycle-ii
- [LeetCode]93. Linked List Cycle II查找链表中环的起始节点
- Linked List Cycle leetcode II java (寻找链表环的入口)
- LeetCode-Linked List Cycle II -有环链表-推理
- leetcode_c++:链表:Linked List Cycle II(142)
- 【LeetCode题解】142_环形链表2(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 & Linked List Cycle II——单链表中的环
- leetcode---linked-list-cycle-ii---链表
- 【题解】【链表】【Leetcode】Linked List Cycle II
- [Leetcode] Linked list cycle ii 判断链表是否有环