转载请注明:http://blog.csdn.net/ict2014/article/details/17536123
原题如下:
题目解析:
这道题目是“判断一个单链表是否有环?”,最经典的做法就是设定两个指针,一个快指针,一个慢指针,快指针每次走两步,慢指针每次走一步,如果存在环的时候,快慢指针会重合。如果没有环,则会走到链表的末尾。
题目代码:
/**
* 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) {
if(head == NULL || head->next == NULL){
return false;
}
ListNode* slow = head;
ListNode* fast = head;
while(fast != NULL && fast->next != NULL){
fast = fast->next->next;
slow = slow->next;
if(slow == fast){
return true;
}
}
return !(fast == NULL || fast->next == NULL);
}
};