給定一個鏈表,讓我們判斷是否是有環
環形鏈表
分析: 可以采用雙指標的方法來進行判斷,一個快指標,一個慢指標
代碼如下:
/**
* 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 *fast,*slow;
fast=slow=head;
while(fast!=NULL&&fast->next!=NULL){
fast=fast->next->next;
slow=slow->next;
if(fast==slow){
return true;
}
}
return false;
}
};
這還有給進階的,求環形的起點,我們只需要重新設定slow=head,然后再相遇就是起點
代碼如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(head==NULL) return NULL;
ListNode *fast,*slow;
fast=slow=head;
while(fast!=NULL&&fast->next!=NULL){
fast=fast->next->next;
slow=slow->next;
if(fast==slow){
break;
}
}
if(fast!=slow||fast==NULL||fast->next==NULL){
return NULL;
}
slow=head;
while(slow!=fast){
slow=slow->next;
fast=fast->next;
}
return slow;
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/243938.html
標籤:其他
上一篇:Android音視頻【五】H265/HEVC&碼流結構
下一篇:素數字母
