【LeetCode】Linked List Cycle II
来源:互联网 发布:淘宝店铺宝贝数量 编辑:程序博客网 时间:2024/05/22 05:20
Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull
.
Follow up:
Can you solve it without using extra space?
思路:
首先利用快慢指针判断是否存在循环(快慢指针是否会相遇),如果存在,那么第一个循环开始的节点一定位于head和快慢指针相遇节点之间。寻找方法就是设置一个指针p从头部节点开始,沿着链表移动,再让另外一个指针绕着cycle不断转圈,如果移动过程中碰到p,则p就是循环开始的第一个节点,如果饶了一圈还没有碰到,就让p移到下一个节点,知道相遇。
class Solution {public: ListNode *detectCycle(ListNode *head) { if (head == NULL) { return NULL; } ListNode *slow, *fast; slow = fast = head; do { fast = fast->next ? fast->next->next : fast->next; slow = slow->next; }while (fast != NULL && fast != slow); if (fast == NULL) { // no cycle return NULL; } while (fast != head) { if ((fast = fast->next) == slow) { head = head->next; } } return fast; }};
0 0
- 【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
- [LeetCode] Linked List Cycle II
- Linux程序设计笔记(第4章 Linux环境)
- 设置可编辑
- javascript学习笔记
- OCP试题解析之053-17 CONFIGURE CONTROLFILE AUTOBACKUP ON
- 第十章 10.5.3节练习 & 10.6节练习
- 【LeetCode】Linked List Cycle II
- 音效和音乐播放要用到的方法
- 把质量控制工作往前推进(1)——安装sonarqube
- Boost Asio 1.56 学习之同步定时器
- eclipse中格式化代码快捷键Ctrl+Shift+F失效的解决办法
- Loadrunner中集合点详解
- Android隐藏输入法键盘(hideSoftInputFromInputMethod没有效果)
- STL array中的end方法(11)
- ubuntu nfs服务器