Given A linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Beginning to think that this problem only need to pay attention not to use extra space, so wrote a time complexity of O (n^2) brute force search algorithm, as follows:
/** * Dumped, time Limit exceeded*/classSolution { Public: BOOLHascycle (ListNode *head) { if(!head | |!head->next)return false; ListNode*pre =Head; ListNode*cur = head->Next; while(cur) {Pre=Head; while(Cur->next! = Pre && Pre! =cur) {Pre= pre->Next; } if(Cur->next = = Pre && pre! = cur)return true; Cur= cur->Next; } return false; }};
But OJ still do not pass, because time Limit exceeded, or need to reduce the complexity of the O (n), so the Internet search the method of the great God, found that it is very magical. You only need to set two pointers, a slow pointer each step, and a two-step fast pointer, if there is a ring in the chain, two pointers will eventually meet. It was so ingenious, if I could not think of it. The code is as follows:
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: BOOLHascycle (ListNode *head) { if(!head | |!head->next)return false; ListNode*slow =Head; ListNode*fast =Head; while(Slow &&fast) {Slow= slow->Next; Fast= fast->Next; if(!fast)return false; Fast= fast->Next; if(slow = = fast)return true; } return false; }};
[Leetcode] Linked ring in list Cycle single-linked list