[LeetCode] Linked List Cycle II Solution
来源:互联网 发布:阿里云 盘古 编辑:程序博客网 时间:2024/06/06 03:05
Given a linked list, return the node where the cycle begins, if there is no cycle, return null.
Follow up: could you solve it without using extra space?
Ideas:
1. Check whether the linked list has cycle, use slow and fast pointer. ([LeetCode] Linked List Cycle)
2. if has, then,
Assume slow pointer goes n steps, then, fast pointer goes 2n steps.
Assume head to cycle starter are m steps, then 2n = length + (n - m),
So, n = length - m; m = length - n
So. flow the fast pointer, Slow pointer to the starter is the same length between the head to starter
/** * 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) { if(!head) return head; if(head->next == NULL) return NULL; ListNode *pSlow = head, *pFast = head; //get the node which slow and fast encounter while(pFast!= NULL && pFast->next != NULL) { pSlow = pSlow->next; pFast = pFast->next->next; if(pFast == pSlow) { break; } } //if encouter, pSlow go n step, pFast go 2n step. // if head to the starter is m step, list's length is length // then 2n = length + (n - m) //So. length = n + m; n = length - m; m = length - n; // Slow pointer to the starter is the same length between the head to starter if(pFast== pSlow) { pFast = head; //let pFast encounter pSlow again. // this node is the starter of cycle while(pFast != pSlow) { pFast = pFast->next; pSlow = pSlow->next; } return pSlow; } return NULL; } private: bool hasCycle(ListNode *head) { if(!head) return false; if(head->next == NULL) return false; ListNode *pSlow = head, *pFast = head; while(pFast!=NULL && pFast->next !=NULL) { pSlow = pSlow->next; pFast = pFast->next->next; if(pSlow == pFast) { return true; } } return false; }};
0 0
- [LeetCode] Linked List Cycle II, Solution
- [LeetCode] Linked List Cycle II Solution
- [LeetCode] Linked List Cycle II, Solution
- [LeetCode] Linked List Cycle, Solution
- 【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
- hdu 2824 Dogs(BFS, 优先队列优化)
- [Leetcode]Path Sum&Path Sum II
- FlaskBB阅读笔记(一)
- MATLAB学习第一天 脚本的使用方法
- USACO Wisconsin Squares 解题报告
- [LeetCode] Linked List Cycle II Solution
- [Leetcode]Balanced Binary Tree
- [LeetCode] Linked List Cycle
- HDU 4819 Mosaic 二维线段树
- 散列查找:C语言线性探查与拉链存储的实现
- 设计模式中类的关系
- 九分裤过来可好看
- 大家好才是真的好
- qlrwar组装作卓踪姿