Linked List Cycle II
来源:互联网 发布:模具设计软件 编辑:程序博客网 时间:2024/05/22 05:06
描述
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?
中文找到链表换开始的节点:
分析:
两个指针ptr1和ptr2,都从链表头开始走,ptr1每次走一步,ptr2每次走两步,等两个指针重合时,就说明有环,否则没有。如果有环的话,那么让ptr1指向链表头,ptr2不动,两个指针每次都走一步,当它们重合时,所指向的节点就是环开始的节点。
图示:
假设在红色凸起的地方相遇了。
F走的路程应该是S的两倍
S = x + y
F = x + y + z + y = x + 2y + z
2*S = F
2x+2y = x + 2y + z
得到x = z
也就是从head到环开始的路程 = 从相遇到环开始的路程
那么。。。只要S和F相遇了,我们拿一个从头开始走,一个从相遇的地方开始走
两个都走一步,那么再次相遇必定是环的开始节点!
class Solution {public: ListNode *detectCycle(ListNode *head) { ListNode* ptr1,* ptr2; if(head == NULL) return NULL; ptr1 = head ; ptr2 = head; while(ptr2->next != NULL && ptr2->next->next != NULL) { ptr1 = ptr1->next; ptr2 = ptr2->next->next; if(ptr1 == ptr2) { ptr1 = head; while(ptr1 != ptr2) { ptr2 = ptr2->next; ptr1 = ptr1->next; } return ptr1; } } return NULL; }};
0 0
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Color the fence
- OC中的Block,多态
- hdu5319 模拟水题
- 【项目经验】文本验证
- 开入与开出
- Linked List Cycle II
- asoc dapm相关
- hdu 3047 简单的带权并查集
- UVA - 1343 The Rotation Game
- 暑假的第一次测试(三)
- 概率论与数理统计--假设检验
- 稳态与暂态
- 区间型动态规划
- linux scopy