【题目】
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 *pre=head,*last=head;
if(NULL==head)return false;
while(pre&&last&&(pre->next)&&(last->next)&&(last->next->next)){
if(pre==(last->next))return true;
pre=pre->next;
last=last->next->next;
if(pre==last)return true;
}
return false;
}
};
【总结】
1.基本思想:设立快慢两个指针,若存在环,俩指针必相遇
2.指针的使用:
while(pre&&last&&(pre->next)&&(last->next)&&(last->next->next))
这句中的判断条件,要先判断last->next,再判断last->next->next,避免出现非法指针