網(wǎng)站首頁 編程語言 正文
題目描述:
輸入兩個遞增的鏈表,單個鏈表的長度為n,合并這兩個鏈表并使新鏈表中的節(jié)點仍然是遞增排序的。
數(shù)據(jù)范圍: n為0~1000,節(jié)點值為-1000~1000
要求:空間復(fù)雜度 O(1),時間復(fù)雜度 O(n)
如輸入{1,3,5},{2,4,6}時,合并后的鏈表為{1,2,3,4,5,6},所以對應(yīng)的輸出為{1,2,3,4,5,6},轉(zhuǎn)換過程如下圖所示:
或輸入{-1,2,4},{1,3,4}時,合并后的鏈表為{-1,1,2,3,4,4},所以對應(yīng)的輸出為{-1,1,2,3,4,4},轉(zhuǎn)換過程如下圖所示:
示例:
輸入:
{1,3,5},{2,4,6}
返回值:
{1,2,3,4,5,6}
解題思路:
本題考察數(shù)據(jù)結(jié)構(gòu)鏈表的使用。有兩種解法:
- 遍歷比較。建立一個新的頭節(jié)點head后,用cur指針指向下一節(jié)點;然后依次比較兩個子鏈表節(jié)點的值大小,誰小先塞誰,塞完就將其指向下一個節(jié)點;直到某個子鏈表遍歷完,將cur的next指向沒遍歷完的那個鏈表當(dāng)前的節(jié)點。
- 遞歸。從pHead1和pHead2的頭節(jié)點開始比較,誰小就返回誰,然后其下一個指向,指向Merge函數(shù)的結(jié)果,Merge輸入的兩個鏈表為小的一方的next和大的一方的頭節(jié)點,也就是用下一個值和它繼續(xù)比誰更小;依次類推,遞歸中斷的標(biāo)志是有其中一個子鏈表指向nullptr,返回另一方即可。
測試代碼:
解法一,遍歷:
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: ListNode* Merge(ListNode* pHead1, ListNode* pHead2) { ListNode *head=new ListNode(-1); ListNode *cur=head; while(pHead1&&pHead2) { if(pHead1->val<=pHead2->val) { cur->next=pHead1; pHead1=pHead1->next; } else{ cur->next=pHead2; pHead2=pHead2->next; } cur=cur->next; } cur->next=pHead1?pHead1:pHead2; return head->next; } };
解法二,遞歸:??
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: ListNode* Merge(ListNode* pHead1, ListNode* pHead2) { if(!pHead1) return pHead2; if(!pHead2) return pHead1; if(pHead1->val<=pHead2->val) { pHead1->next=Merge(pHead1->next,pHead2); return pHead1; } else{ pHead2->next=Merge(pHead1,pHead2->next); return pHead2; } } };
原文鏈接:https://blog.csdn.net/zhaitianbao/article/details/121767253
相關(guān)推薦
- 2022-07-16 構(gòu)建npm配置包
- 2022-07-24 Golang?CSP并發(fā)機制及使用模型_Golang
- 2022-10-04 混合棧跳轉(zhuǎn)導(dǎo)致Flutter頁面事件卡死問題解決_IOS
- 2023-01-05 Kotlin?泛型邊界型變及星投影使用詳解_Android
- 2023-07-02 Linux系統(tǒng)下如何實現(xiàn)修改主機名_Linux
- 2022-08-15 gin框架中使用websocket發(fā)送消息及群聊
- 2023-06-05 Go實現(xiàn)共享庫的方法_Golang
- 2022-03-14 【錯誤記錄/html】Response to preflight request doesn‘t p
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支