合并两个排序的链表

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

复制代码
 1 /*
 2 struct ListNode {
 3     int val;
 4     struct ListNode *next;
 5     ListNode(int x) :
 6             val(x), next(NULL) {
 7     }
 8 };*/
 9 class Solution {
10 public:
11     ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
12     {
13         ListNode* res=NULL;
14         if(pHead1==NULL&&pHead2==NULL) return res;
15         if(pHead1==NULL){
16             res=pHead2;
17             return res;
18         }
19         if(pHead2==NULL){
20             res=pHead1;
21             return res;
22         }
23         ListNode* tmp;
24         if(pHead1->val>pHead2->val){
25              res=pHead2;
26             pHead2=pHead2->next;
27         }
28            
29         else{
30             res=pHead1;
31             pHead1=pHead1->next;
32         }
33             
34         tmp=res;
35         while(pHead1!=NULL&&pHead2!=NULL){
36             if(pHead1->val<pHead2->val){
37                 tmp->next=pHead1;
38                 tmp=tmp->next;
39                 pHead1=pHead1->next;
40             }
41             else{
42                 tmp->next=pHead2;
43                 tmp=tmp->next;
44                 pHead2=pHead2->next;
45             }
46         }
47         if(pHead1!=NULL)
48             tmp->next=pHead1;
49         if(pHead2!=NULL)
50             tmp->next=pHead2;
51         return res;
52     }
53 };
复制代码

 

posted @   鸭子船长  阅读(153)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示