Linked List Cycle II
来源:互联网 发布:u盘坏了怎么恢复数据 编辑:程序博客网 时间:2024/06/10 06:18
Linked List Cycle II
Problem
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.
Follow up:
Can you solve it without using extra space?
问题
给定一个链表,返回环的起始结点,如果链表不包含环,则返回空。
注意: 不能修改链表
扩展: 不使用辅助存储空间找到链表中环的起始结点。
解题思路
此题目是链表中的环问题扩展。假设经过m步之后,快慢指针相遇。则由链表中的环问题分析可知: 此时快指针走过的路程为m,慢指针走过的路程为2m。此时如果让快指针回到链表头,两个指针都一次走一步。则经过n步(n不大于m)在环的起点处,两个指针将再次相遇。如下图所示:
代码(C++)
class Solution {public: ListNode *detectCycle(ListNode *head) { if (!head || !(head->next)) return NULL; ListNode* slow = head; ListNode* fast = head; bool hasCycle = false; while(fast && fast->next){ fast = fast->next->next; slow = slow->next; if(slow == fast){ hasCycle = true; break; } } if (hasCycle){ fast = head; while(slow != fast){ slow = slow->next; fast = fast->next; } return slow; } 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
- Android仿射密码破译app
- iOS_UITextField整理
- 2016SDAU编程练习三1015
- 我爱学Java之四种引用类型(强软弱虚)
- linux下通过sed命令直接修改文件内容
- Linked List Cycle II
- jsoncpp解析拼装数组
- Latex插入图片报错问题处理集锦
- 最大子段和
- Android Studio快速导入SO文件与jAR包
- LR之run-time settings设置
- HDU 4165 Pills
- ROS机器人直行1米,接着旋转180°,再返回到起始点。之二
- bash & && || ; & 使用方法