總是不能夠考慮到所有的情況,都快吐了
總結:1.判斷鏈表是否成環,主要看下一個節點是否爲NULL,2.快慢指針
1.首先沒有節點、只有一個節點,肯定沒有環
2.有兩個節點,如果沒有環,head->next->next==NULL;所以1,2兩種情況可以放到一起判斷
3.兩個及兩個以上節點,如果快慢指針相遇,那就是有環,如果下一個節點或者下下一個節點爲NULL,就說明沒有環,退出循環,返回false
/**
* 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||head->next->next==NULL)
return false;
//鏈表有兩個及以上的元素
ListNode* fast=head->next->next;
ListNode* slow=head;
while(slow!=fast)
{
if(fast->next==NULL||fast->next->next==NULL)
return false;
fast=fast->next->next;
slow=slow->next;
}
return true;
}
};
作者:huuh
鏈接:https://leetcode-cn.com/problems/linked-list-cycle/solution/jian-chi-jiu-shi-sheng-li-ao-li-gei-by-huuh/
來源:力扣(LeetCode)
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。