2014.1.13 21:24
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Solution:
The problem indicated that you shouldn't use extra space. And you might be wondering why you should use extra space if you could just use two pointers and let the faster one chase up the slower one.
If extra space is allowed, you can use a hash-table to record the addresses of the nodes. There will be duplicate address if the list contains a cycle.
I guess you're more familiar with the chasing method, which uses extra chasing time to avoid the space usage in hashing.
Time complexity is O(n), space complexity is O(1).
Accepted code:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 bool hasCycle(ListNode *head) { 12 // IMPORTANT: Please reset any member data you declared, as 13 // the same Solution instance will be reused for each test case. 14 if(head == nullptr){ 15 return false; 16 } 17 18 ListNode *p1, *p2; 19 20 p1 = p2 = head; 21 while(true){ 22 if(p1->next == nullptr){ 23 return false; 24 } 25 if(p2->next == nullptr || p2->next->next == nullptr){ 26 return false; 27 } 28 29 p1 = p1->next; 30 p2 = p2->next->next; 31 if(p1 == p2){ 32 // Same address, same node 33 // There is a cycle in the list 34 return true; 35 } 36 } 37 } 38 };