【题目】
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
【题意】
判断一个单向链表是否有环
【思路】
维护两个指针p1和p2,p1每次向前移动一步,p2每次向前移动两步如果p2能够追上p1,则说明链表中存在环
【代码】
/**
* 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*p1=head;
ListNode*p2=head;
while(p2){
//p1向前走一步
p1=p1->next;
//p2向前走两部
p2=p2->next;
if(p2)p2=p2->next;
//判断p2是否追上了p1
if(p2 && p2==p1)return true;
}
return false;
}
};