Follow up:
Can you solve it without using extra space?
Solution: classic interview question, which can be solve by slow-fast pointers. The speed of fast pointer is twice of speed of slow one. If a cycle exists, two pointers would meet somewhere. [here is a follow-up question]
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: bool hasCycle(ListNode *head) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if(!head || !head->next || !head->next->next) return false; ListNode* slow = head->next; ListNode* fast = head->next->next; while(slow!=fast){ if(!fast->next || !fast->next->next) return false; slow=slow->next; fast=fast->next->next; } return true; } };
No comments:
Post a Comment