Linked List Cycle II
2013-11-03 10:05
281 查看
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到环入口的距离为a,相遇点到环入口的距离为b,换的周长为r,则第一次相遇时有
2*(a+b) = a + b + nr
a = nr - b
也就是说如果从相遇点和head处同时出发两个指针,步数一样,那么就会在环入口相遇,据此可以获得入口的指针
代码
null.
Follow up:
Can you solve it without using extra space?
思路:
在上一题的基础上,假设head到环入口的距离为a,相遇点到环入口的距离为b,换的周长为r,则第一次相遇时有
2*(a+b) = a + b + nr
a = nr - b
也就是说如果从相遇点和head处同时出发两个指针,步数一样,那么就会在环入口相遇,据此可以获得入口的指针
代码
ListNode *detectCycle(ListNode *head) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if(head == NULL) return NULL; if(head->next == NULL) return NULL; ListNode *slow = head, *fast = head; while(true){ if(fast && fast->next){ fast = fast->next->next; } else{ return NULL; } slow = slow->next; if(fast == slow) break; } ListNode *p1 = head, *p2 = slow; while(true){ if(p1 == p2) return p1; p1 = p1->next; p2 = p2->next; } }
相关文章推荐
- Linked List Cycle II (leetcode)
- Linked List Cycle II
- Leetcode: Linked List Cycle II
- *Linked List Cycle II
- leetcode_c++:链表:Linked List Cycle II(142)
- LeetCode:Linked List Cycle && Linked List Cycle II
- leetcode — linked-list-cycle-ii
- [LeetCode] Linked List Cycle II
- Linked List Cycle II
- [LeetCode] Linked List Cycle II
- Linked List Cycle II
- leetcode — linked-list-cycle-ii
- Leetcode 142 Linked List Cycle II
- Leetcode78: Linked List Cycle II
- LeetCode:Linked List Cycle II
- Linked List Cycle I和II 以及扩展
- Leetcode在线编程linked-list-cycle-ii
- [leetcode] Linked List Cycle II
- LeetCode 142: Linked List Cycle II
- Linked List Cycle II - LeetCode