lintcode-103-带环链表 II
2017-07-14 09:14
330 查看
带环链表 II
给定一个链表,如果链表中存在环,则返回到链表中环的起始节点的值,如果没有环,返回null。
样例
给出 -21->10->4->5, tail connects to node index 1,返回10挑战
不使用额外的空间标签
链表 两根指针思路
参考lintcode-102-带环链表首先,利用快慢指针判断有无环,若遇到slow == fast时,存在环,跳出循环;
然后,使fast=head,slow不变,slow与fast同步移动,直至再次相遇,即是链表中环的起始节点。
code
/** * Definition of ListNode * class ListNode { * public: * int val; * ListNode *next; * ListNode(int val) { * this->val = val; * this->next = NULL; * } * } */ class Solution { public: /** * @param head: The first node of linked list. * @return: The node where the cycle begins. * if there is no cycle, return null */ ListNode *detectCycle(ListNode *head) { // write your code here ListNode * fast = head, *slow = head, *result = NULL; while(fast != NULL && fast->next != NULL) { slow = slow->next; fast = fast->next->next; if(fast == slow) { break; } } if(fast != NULL && fast->next != NULL) { fast = head; while(fast != slow) { slow = slow->next; fast = fast->next; } result = fast; } return result; } };
相关文章推荐
- LintCode(103)带环链表 II
- lintcode(103)带环链表 II
- LintCode_103_带环链表 II
- lintcode--带环链表II
- LintCode-带环链表 II
- *[Lintcode]带环链表 II
- [LintCode] 带环链表 II Linked List Cycle II
- 带环链表-LintCode
- 删除排序链表中的重复数字 II -LintCode
- lintcode 带环链表(102)
- LintCode 带环链表(快慢指针法)
- LintCode-[中等] 221. 链表求和 II
- LintCode-删除排序链表中的重复数字 II
- LeetCode Linked List Cycle II(找到带环单向链表的环起始位置)
- [LintCode 102] 带环链表(Python)
- lintcode-113-删除排序链表中的重复数字 II
- lintcode(102)带环链表
- lintcode-221-链表求和 II
- LintCode-----36.翻转链表 II
- lintcode,翻转链表 II