Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
解題思路:
1、最基本的辦法是用一個set來存儲所有已經出現過的指針。若出現重復,則表示有環,若沒有重復,則沒有環。
/** * 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) { ListNode* p = head; set2、雙指針方法。設立兩個指針,一個指針每次走一步,另外一個指針每次走兩步。若兩個指針相遇,表示有環。不相遇,則表示無環。具體見:http://blog.csdn.net/kangrydotnet/article/details/45154927s; while(p!=NULL){ if(s.find(p)!=s.end()){ return true; } s.insert(p); p=p->next; } return false; } };
/** * 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) { ListNode* one = head; ListNode* two = head; while(two!=NULL && two->next!=NULL){ one=one->next; two=two->next->next; if(one==two){ return true; } } return false; } };