網站首頁 編程語言 正文
題目描述:
輸入兩個遞增的鏈表,單個鏈表的長度為n,合并這兩個鏈表并使新鏈表中的節點仍然是遞增排序的。
數據范圍: n為0~1000,節點值為-1000~1000
要求:空間復雜度 O(1),時間復雜度 O(n)
如輸入{1,3,5},{2,4,6}時,合并后的鏈表為{1,2,3,4,5,6},所以對應的輸出為{1,2,3,4,5,6},轉換過程如下圖所示:
或輸入{-1,2,4},{1,3,4}時,合并后的鏈表為{-1,1,2,3,4,4},所以對應的輸出為{-1,1,2,3,4,4},轉換過程如下圖所示:
示例:
輸入:
{1,3,5},{2,4,6}
返回值:
{1,2,3,4,5,6}
解題思路:
本題考察數據結構鏈表的使用。有兩種解法:
- 遍歷比較。建立一個新的頭節點head后,用cur指針指向下一節點;然后依次比較兩個子鏈表節點的值大小,誰小先塞誰,塞完就將其指向下一個節點;直到某個子鏈表遍歷完,將cur的next指向沒遍歷完的那個鏈表當前的節點。
- 遞歸。從pHead1和pHead2的頭節點開始比較,誰小就返回誰,然后其下一個指向,指向Merge函數的結果,Merge輸入的兩個鏈表為小的一方的next和大的一方的頭節點,也就是用下一個值和它繼續比誰更小;依次類推,遞歸中斷的標志是有其中一個子鏈表指向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
- 上一篇:C++基礎概念講述_C 語言
- 下一篇:C#?微信支付回調驗簽處理的實現_C#教程
相關推薦
- 2022-10-18 C++數據結構之二叉搜索樹的實現詳解_C 語言
- 2022-05-24 一起來學習C語言的輸入和輸出_C 語言
- 2023-02-06 Python繪圖庫之pyqtgraph的用法詳解_python
- 2022-11-01 zxing二維碼位矩陣轉換成Bitmap位圖的實戰教程_Android
- 2022-08-30 C++超詳細介紹模板_C 語言
- 2022-01-22 oracle之連接查詢和子查詢
- 2023-06-03 C++11學習之右值引用和移動語義詳解_C 語言
- 2022-04-22 element的el-drawer預留操作欄問題
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支