leetcode Linked List Cycle & Linked List Cycle II
来源:互联网 发布:雷云mac版安装失败 编辑:程序博客网 时间:2024/04/30 22:28
Linked List Cycle 要判断链表是否有环,通过设置快慢两个指针,慢的指针没走一步快的指针走两步,这样,如果有环,两个指针必然会相遇,否则,快的指针直到链尾就表示无环,这是因为对于一个链有环,由于快指针经环会绕道慢指针的后面,而每一步快指针都比慢指针快一步,二者最终必然相遇
class Solution {public:bool hasCycle(ListNode *head) { if(head==NULL||head->next==NULL)return false; ListNode *p=head,*q=head; while(p&&p->next){ q=q->next; p=p->next->next; if(p==q)return true; } return !(p==NULL||p->next==NULL); }};Linked List Cycle II 需要在判断有环的基础上继续求得环的开始位置,只需要在快慢指针相遇后,将慢指针移到连头,两个指针同时一步一步后移,当二者再次相遇,即可找到环的开始位置
bool hasCycle(ListNode *head) { if(head==NULL||head->next==NULL)return false; ListNode *p=head,*q=head; while(p&&p->next){ q=q->next; p=p->next->next; if(p==q)return true; } return !(p==NULL||p->next==NULL); }class Solution {public: ListNode *detectCycle(ListNode *head) { //if(head==NULL||head->next==NULL)return NULL; if(!hasCycle(head))return NULL; ListNode *p=head,*q=head; int i=0; while(p&&p->next){ i++; q=q->next; p=p->next->next; if(p==q)break; } q=head; while(p!=q){q=q->next;p=p->next;} return q; }};
0 0
- LeetCode[Linked List]: 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
- 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
- Linked List Cycle II -- LeetCode
- LeetCode Linked List Cycle II
- 求多个选择情况下的函数值
- poj3897
- C#使用多维数组
- 本地表、远程表的复制操作(SQL命令行)
- OpenCV2马拉松第15圈——边缘检测(Laplace算子,LOG算子)
- leetcode Linked List Cycle & Linked List Cycle II
- 如何搭建私有云平台
- Google CodeJam 2014 Round 1C
- 创新实验室实习生每周工作总结【实习第六周】
- 第11周 项目一 1.2 班长和学生的信息 体验版
- 周报(第六周)
- C语言优化实例:消除多级指针的间接访问
- ENetwork Chapter 6 - CCNA Exploration (Version 4.0)
- poj 1836 (动态规划之最长上升子序列)