Given a linked list, determine if it has a cycle in it.
Follow up: Can you solve it without using extra space?
思考:快慢指針,快指針一次走兩步,慢指針一次一步。若快指針跟慢指針指向同一個結點,則有環。若快指針到達鏈表末尾即指向NULL,說明沒有環。
/*** 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) return false;ListNode *p=head;ListNode *q=p->next;while(q&&q->next){if(p==q) return true;else{q=q->next->next;p=p->next;}}return false;}
};