Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
/**
* 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;
}
};LeetCode: Linked List Cycle [141],布布扣,bubuko.com
LeetCode: Linked List Cycle [141]
原文地址:http://blog.csdn.net/harryhuang1990/article/details/35596851