题目
判断单链表里是否有环
分析
用两个指针P1和P2,P1每次走一步,P2每次走两步,如果链表中有环,两个指针一定会在环中相遇。
C代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
if(head==NULL){
return false;
}
struct ListNode* quick = head;
struct ListNode* slow = head;
do{
if(quick==NULL || quick->next==NULL)
return false;
quick = quick->next->next;
slow = slow->next;
}while(quick!=slow);
return true;
}
C++代码
/**
* 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){ //空指针和只有一个结点,输出false
return false;
}
ListNode* quick = head;
ListNode* slow = head;
while(quick!=NULL && quick->next!=NULL){ //注意循环结束条件,因为quick每次走两步
quick = quick->next->next;
slow = slow->next;
if(quick == slow){
return true;
}
}
return false;
}
};