文章目錄
- 前言
- 一、鏈表分割
- 二、環形鏈表I
- 三、環形鏈表II
- 四、鏈表的回文結構
- 五、隨機鏈表的復制
前言
一、鏈表分割
牛客網CM11:鏈表分割- - -點擊此處傳送
題解:
思路圖:
代碼:
二、環形鏈表I
力扣141:環形鏈表- - -點擊此處傳送
思路圖:
擴展問題:
代碼:
bool hasCycle(struct ListNode *head) {struct ListNode*fast=head,*slow=head;while(fast && fast->next){//slow走一步slow=slow->next;//fast走兩步fast=fast->next->next;//若相等(相遇)則有環,返回true并退出程序if(fast==slow){return true;}}//否則無環return false;
}
三、環形鏈表II
力扣142:環形鏈表II- - -點擊此處傳送
題解:
思路圖:
代碼:
struct ListNode *detectCycle(struct ListNode *head) {struct ListNode*fast=head;struct ListNode*slow=head;while(fast && fast->next){slow=slow->next;fast=fast->next->next;if(fast==slow){struct ListNode*meet=slow;while(head != meet){head=head->next;meet=meet->next;}return meet;}}return NULL;
}
四、鏈表的回文結構
牛客網OR36:鏈表的回文結構- - -點擊此處傳送
思路圖:
代碼:
struct ListNode*reverseList(struct ListNode*head){struct ListNode*cur=head;struct ListNode*newhead=NULL;while(cur){struct ListNode*next=cur->next;cur->next=newhead;newhead=cur;cur=next;}return newhead;}struct ListNode*middleNode(struct ListNode*head){struct ListNode*slow=head;struct ListNode*fast=head;while(fast && fast->next){slow=slow->next;fast=fast->next->next;}return slow;}bool chkPalindrome(ListNode* head) {struct ListNode*mid=middleNode(head);struct ListNode*rhead=reverseList(mid);while(head && rhead){if(head->val != rhead->val)return false;head=head->next;rhead=rhead->next;}return true;}
五、隨機鏈表的復制
力扣138:隨機鏈表的復制- - -點擊此處傳送
思路圖:
代碼:
struct Node* copyRandomList(struct Node* head)
{struct Node*cur=head;while(cur){struct Node*copy=(struct Node*)malloc(sizeof(struct Node));copy->val=cur->val;copy->next=cur->next;cur->next=copy;cur=copy->next;} cur=head;while(cur){struct Node*copy=cur->next;if(cur->random==NULL){copy->random=NULL;}else{copy->random=cur->random->next;}cur=copy->next;}cur=head;struct Node*newhead=NULL;struct Node*tail=NULL;while(cur){struct Node*copy=cur->next;struct Node*next=copy->next;if(tail==NULL){newhead=tail=copy;}else{tail->next=copy;tail=tail->next;}cur->next=next;cur=next;}return newhead;
}