文章目錄
- 前言
- 一、反轉鏈表
- 二、移除鏈表元素
- 三、鏈表中倒數第K個結點
- 四、相交鏈表
- 五、鏈表的中間結點
前言
一、反轉鏈表
力扣206:反轉鏈表- - -點擊此處傳送
思路圖:
方法一:改變指向
方法二:
代碼:
//方法一
//改變指向
struct ListNode* reverseList(struct ListNode* head) {//判斷空if(head==NULL){return NULL;}struct ListNode*n1,*n2,*n3;n1=NULL;n2=head;n3=head->next;while(n2){n2->next=n1;n1=n2;n2=n3;if(n3){n3=n3->next;}}return n1;
}//方法二
//頭插
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;
}
二、移除鏈表元素
力扣203:移除鏈表元素- - -點擊此處傳送
思路圖:
方法2:
當然這題也可以使用帶哨兵位的結點
代碼
//方法1:
struct ListNode* removeElements(struct ListNode* head, int val) {struct ListNode*cur=head;struct ListNode*newhead=NULL;struct ListNode*tail=NULL;while(cur){if(cur->val!=val){if(tail==NULL){newhead=tail=cur;}else{tail->next=cur;tail=tail->next;}cur=cur->next;}else{struct ListNode*tmp=cur;cur=cur->next;free(tmp);}}if(tail)tail->next=NULL;return newhead;
}//方法2:
struct ListNode* removeElements(struct ListNode* head, int val) {struct ListNode* cur=head;struct ListNode* tail=NULL;struct ListNode* newhead=NULL;//哨兵位newhead=tail=(struct ListNode*)malloc(sizeof(struct ListNode));while(cur){if(cur->val!=val){//尾插tail->next=cur;tail=tail->next;cur=cur->next;}else{struct ListNode*tmp=cur;cur=cur->next;free(tmp);}}tail->next=NULL;struct ListNode*tmp=newhead;newhead=newhead->next;free(tmp);return newhead;
}
三、鏈表中倒數第K個結點
牛客網:鏈表中倒數第K個結點- - -點擊此處傳送
思路圖:
代碼:
//牛客網代碼模型
struct ListNode* FindKthToTail(struct ListNode* pListHead, int k ) {// write code herestruct ListNode* fast=pListHead;struct ListNode* slow=pListHead;while(k--){//空鏈表if(fast==NULL)return NULL;fast=fast->next;}while(fast){fast=fast->next;slow=slow->next;}return slow;
}
四、相交鏈表
力扣160:相交鏈表- - -點擊此處傳送
思路圖:
代碼:
//思路2:
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {struct ListNode*curA=headA;struct ListNode*curB=headB;int lenA=0;int lenB=0;//計算鏈表A的長度while(curA->next){lenA++;curA=curA->next;}//計算鏈表B的長度while(curB->next){lenB++;curB=curB->next;}//無交點if(curA!=curB){return NULL;}//用絕對值求出差值int n=abs(lenA-lenB);struct ListNode*longList=headA;struct ListNode*shortList=headB;//若B長if(lenB>lenA){//長鏈表為BlongList=headB;//短鏈表為AshortList=headA;}//讓長鏈表B先走差值while(n--){longList=longList->next;}//兩鏈表一起走while(longList!=shortList){longList=longList->next;shortList=shortList->next;}return longList;
}
五、鏈表的中間結點
力扣876:鏈表的中間結點- - -點擊此處傳送
思路圖:
代碼:
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;
}