合并单链表,输出单链表中间元素,判断是否有环等
生活随笔
收集整理的這篇文章主要介紹了
合并单链表,输出单链表中间元素,判断是否有环等
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
本博文內(nèi)容為單鏈表相關(guān)的筆試題,轉(zhuǎn)載請(qǐng)注明轉(zhuǎn)載處,否則必究
1. 合并兩個(gè)有序的單鏈表成一個(gè)有序的單鏈表
方法分為遞歸實(shí)現(xiàn)與非遞歸實(shí)現(xiàn),兩種方法都不額外開辟 內(nèi)存空間
鏈表的數(shù)據(jù)結(jié)構(gòu)在本博客的單鏈表逆轉(zhuǎn),約瑟夫環(huán)等?
遞歸實(shí)現(xiàn):
?
//遞歸實(shí)現(xiàn)合并兩個(gè)有序單鏈表 LinkNode* merge_list(LinkNode *pHead1, LinkNode *pHead2) {if(pHead1==NULL)return pHead2;if(pHead2==NULL)return pHead1;if(pHead1==NULL && pHead2==NULL)return NULL;LinkNode *pMergedHead=NULL;if(pHead1->value<pHead2->value){pMergedHead=pHead1;pMergedHead->next = merge_list(pHead1->next, pHead2);}else {pMergedHead=pHead2;pMergedHead->next=merge_list(pHead1, pHead2->next);}return pMergedHead; }非遞歸實(shí)現(xiàn):
?
?
//非遞歸實(shí)現(xiàn)合并兩個(gè)有序單鏈表(不額外開辟空間) LinkNode* non_merge_list(LinkNode *pHead1, LinkNode *pHead2) {if(pHead1==NULL)return pHead2;if(pHead2==NULL)return pHead1;if(pHead1==NULL && pHead2==NULL)return NULL;LinkNode *pMergedHead = NULL;LinkNode *q=NULL;if(pHead1->value<pHead2->value){pMergedHead=pHead1;pHead1=pHead1->next;}else{pMergedHead=pHead2;pHead2=pHead2->next;} q=pMergedHead;while(pHead1 && pHead2){if(pHead1->value<pHead2->value){q->next=pHead1;pHead1=pHead1->next;}else{q->next=pHead2;pHead2=pHead2->next;}q=q->next;}if(pHead1){while(pHead1){q->next=pHead1;q=q->next;pHead1=pHead1->next;}}if(pHead2){while(pHead2){q->next=pHead2;q=q->next;pHead2=pHead2->next;}}return pMergedHead; }?
?
2 輸出單鏈表中的中間元素(若鏈表節(jié)點(diǎn)個(gè)數(shù)為偶數(shù),則輸出中間兩個(gè)的任意一個(gè))
?
思路:利用兩個(gè)指針從頭節(jié)點(diǎn)開始遍歷,一個(gè)走一步,一個(gè)走兩步,當(dāng)一次走兩步的指針走到鏈表末尾時(shí),此時(shí)一次走一步的指針就指向鏈表的中間節(jié)點(diǎn)
代碼如下:
?
LinkNode* print_mid_node(LinkNode *pHead) {LinkNode *pOne = pHead, *pTwo = pHead;while(1) {pOne = pOne->next;pTwo = pTwo->next->next;if(pTwo==NULL || pTwo->next==NULL)return pOne;} }?
3 判斷單戀表是否有環(huán)
?
思路與第二題一樣,只是結(jié)束條件不一樣,如果當(dāng)一次走一步的指針等于一次走兩步的指針時(shí),則表示該鏈表有環(huán)
代碼如下:
?
bool is_circle_list(LinkNode *pHead) {LinkNode *pOne = pHead, *pTwo = pHead;while(1){pOne = pOne->next;pTwo = pTwo->next->next;if(pOne == pTwo)return true;if(pTwo==NULL || pTwo->next==NULL)return false;} }?
?
總結(jié)
以上是生活随笔為你收集整理的合并单链表,输出单链表中间元素,判断是否有环等的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 关于SQL Tuning的知识体系
- 下一篇: Linq to sql 消除列重复 去重