合并單鏈表,輸出單鏈表中間元素,判斷是否有環等

來源:互聯網
上載者:User

本博文內容為單鏈表相關的筆試題,轉載請註明轉載處,否則必究

1. 合并兩個有序的單鏈表成一個有序的單鏈表

方法分為遞迴實現與非遞迴實現,兩種方法都不額外開闢 記憶體空間

鏈表的資料結構在本部落格的單鏈表逆轉,約瑟夫環等 

遞迴實現:

//遞迴實現合并兩個有序單鏈表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;}

非遞迴實現:

//非遞迴實現合并兩個有序單鏈表(不額外開闢空間)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 輸出單鏈表中的中間元素(若鏈表節點個數為偶數,則輸出中間兩個的任意一個)

思路:利用兩個指標從前端節點開始遍曆,一個走一步,一個走兩步,當一次走兩步的指標走到鏈表末尾時,此時一次走一步的指標就指向鏈表的中間節點

代碼如下:

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 判斷單戀表是否有環

思路與第二題一樣,只是結束條件不一樣,如果當一次走一步的指標等於一次走兩步的指標時,則表示該鏈表有環

代碼如下:

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;}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.