?個人主頁:
鏈表環結構
- 0.前言
- 1.環形鏈表(基礎)
- 2.環形鏈表Ⅱ(中等)
- 3.證明相遇條件及結論
- 3.1 問題1特殊情況證明
- 3.2 問題1普適性證明
0.前言
在這篇博客中,我們將深入探討鏈表環結構的檢測方法:
Floyd算法的原理:如何通過快慢指針檢測環?
環入口的定位:如何找到環的起點?
通過這篇博客,我會對鏈表中的環結構進行相關證明解釋,總結學習。
1.環形鏈表(基礎)
題目鏈接:https://leetcode.cn/problems/linked-list-cycle/description/
題目描述:
代碼實現:
/*** Definition for singly-linked list.* struct ListNode {* int val;* struct ListNode *next;* };*/bool hasCycle(struct ListNode *head) {struct ListNode*slow,*fast;slow = fast = head;while(fast&&fast->next){slow=slow->next;fast=fast->next->next;if(slow==fast)return true;}return false;
}
代碼解釋:
這個題目的實現邏輯比較簡單,我們定義快慢指針來進行實現,fast指針每次走2步,slow指針每次走1步,當快指針和慢指針相遇的時候,如果鏈表中存在環,則返回 true 。否則,返回 false。
2.環形鏈表Ⅱ(中等)
題目鏈接:https://leetcode.cn/problems/linked-list-cycle-ii/description/
題目描述:
代碼實現1:
struct ListNode* detectCycle(struct ListNode* head) {struct ListNode* fast;struct ListNode* slow;fast = slow = head;while (fast && fast->next){//快慢指針依次走slow = slow->next;fast = fast->next->next;if (slow == fast){struct ListNode* start = head;struct ListNode* meet = slow;while (meet != start){meet = meet->next;start = start->next;}return meet;}}return NULL;
}
代碼解釋1:
代碼實現2:
/*** Definition for singly-linked list.* struct ListNode {* int val;* struct ListNode *next;* };*/
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB)
{struct ListNode* tailA=headA,*tailB=headB;int lenA=1,lenB=1;while(tailA){tailA=tailA->next;++lenA;}while(tailB){tailB=tailB->next;++lenB;}int gap=abs(lenA-lenB);struct ListNode* longlist=headA,*shortList=headB;if(lenA<lenB){longlist=headB;shortList=headA;}while(gap--){longlist=longlist->next;}while(longlist!=shortList){longlist=longlist->next;shortList=shortList->next;}return longlist;}struct ListNode *detectCycle(struct ListNode *head) {struct ListNode* fast;struct ListNode* slow;fast=slow=head;while(fast&&fast->next){//快慢指針依次走slow=slow->next;fast=fast->next->next;if(slow==fast){//轉換成求交點struct ListNode* meet=slow;struct ListNode* lt1=meet->next;struct ListNode* lt2=head;meet->next=NULL;return getIntersectionNode(lt1,lt2);}}return NULL;
}
代碼解釋2:
3.證明相遇條件及結論
3.1 問題1特殊情況證明
問題1: 為什么slow走1步,fast走2步,他們會相遇嗎?會不會錯過?請證明
3.2 問題1普適性證明
問題:為什么slow走1步,fast走3步(x>=3),他們會相遇嗎?會不會錯過?請證明
感謝您的閱讀支持!!!
后續會持續更新的!!!
文末投票支持一下!!!