[LeetCode]142. Linked List Cycle II
来源:互联网 发布:功能分析和数据分析 编辑:程序博客网 时间:2024/05/29 11:49
142. Linked List Cycle II
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?
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode *detectCycle(ListNode *head) { // 1.找到环中的任意一个节点 ListNode* oneNode = oneNodeInCycle(head); if(oneNode == NULL) return NULL; // 2.计算环的长度 int len = 1; ListNode* temp = oneNode; while(oneNode->next != temp){ ++len; oneNode = oneNode->next; } // 3.让fast指针先行len步 ListNode* fast = head; ListNode* slow = head; while(len--){ fast = fast->next; } // 4.fast和slow指针下次相遇的节点就是入口节点 while(fast != slow){ fast = fast->next; slow = slow->next; } return fast; } // 如果有环,返回环中一个节点 // 如果没有环,返回NULL ListNode* oneNodeInCycle(ListNode* head){ ListNode* fast = head; ListNode* slow = head; while(fast && fast->next){ fast = fast->next->next; slow = slow->next; if(fast == slow) return fast; } return NULL; }};
阅读全文
0 0
- [LeetCode]141. Linked List Cycle【&142. Linked List Cycle II】
- leetcode--141. Linked List Cycle&&142. Linked List Cycle II
- LeetCode 141. Linked List Cycle && 142. Linked List Cycle II
- 142. Linked List Cycle II leetcode list
- LeetCode 142. Linked List Cycle II
- [LeetCode]142.Linked List Cycle II
- [leetcode] 142.Linked List Cycle II
- [leetcode] 142. Linked List Cycle II
- leetcode 142. Linked List Cycle II
- [Leetcode]142. Linked List Cycle II @python
- [LeetCode]142. Linked List Cycle II
- 142. Linked List Cycle II LeetCode
- LeetCode:142. Linked List Cycle II
- LeetCode--142. Linked List Cycle II
- LeetCode 142. Linked List Cycle II
- LeetCode 142. Linked List Cycle II
- LeetCode *** 142. Linked List Cycle II
- LeetCode 142. Linked List Cycle II
- Mac VmWare CentOS7
- OpenCV imread读取图片失败
- 获得当前时间的几种方法
- 用js写一个简单的聊天室
- 使用友员重载运算符讨论
- [LeetCode]142. Linked List Cycle II
- 设计模式学习笔记(Build模式)
- Eclicpse 快捷键大全
- java设计模式之单例模式
- linux安装禅道(CentOS)
- hdu 6108 小C的倍数问题(同余定理)
- ccf201512-2消除类游戏
- 测试
- JavaScript原型、原型链、对象的创建