[LeetCode]Linked List Cycle II
2013-11-20 14:04
411 查看
/** * 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) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. ListNode* fastWalker = head; if(hasCycle(head, fastWalker)) { ListNode* cur = head; while(cur != fastWalker) { cur = cur->next; fastWalker = fastWalker->next; } return cur; } else return NULL; } private: bool hasCycle(ListNode *head, ListNode*& fastWalker) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. ListNode* slowWalker = head; while(fastWalker && slowWalker) { fastWalker = fastWalker->next; if(fastWalker) fastWalker = fastWalker->next; else break; slowWalker = slowWalker->next; if(fastWalker == slowWalker) return true; } return false; } };
相关文章推荐
- Linked List Cycle II -LeetCode
- 开始刷leetcode day12:Linked List Cycle II
- LeetCode Linked List Cycle II
- Leetcode: Linked List Cycle II
- 63_leetcode_Linked List Cycle II
- LeetCode:Linked List Cycle II
- leetcode笔记--Linked List Cycle II
- LeetCode:Linked List Cycle II
- [Leetcode][python]Linked List Cycle/Linked List Cycle II
- LeetCode——Linked List Cycle II
- (leetcode)Linked List Cycle II
- leetcode 日经贴,Cpp code -Linked List Cycle II
- LeetCode Linked List Cycle && Linked List CycleII
- leetcode:linked_list_cycle_II
- Linked List Cycle II -- leetcode
- LeetCode刷题:Linked List Cycle 及其进阶Linked List Cycle II
- LeetCode 142: Linked List Cycle II
- leetcode Linked List Cycle II
- leetcode: Linked List Cycle II
- 【LeetCode】Linked List Cycle II