剑指office--------合并两个排序的链表

题目描述

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
 
 
 
 
 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         if (pHead1==NULL&&pHead2==NULL)    return NULL;
14         
15         ListNode* node;
16         ListNode* Node;
17         
18         if (pHead1!=NULL&&pHead2!=NULL){
19             if(pHead1->val < pHead2->val){
20                 node=pHead1;
21                 Node=node;
22                 pHead1=pHead1->next;
23             }
24             else{
25                 node=pHead2;
26                 Node=node;
27                 pHead2=pHead2->next;
28             }
29         }
30         else if (pHead1==NULL)    return pHead2;
31         else if (pHead2==NULL)    return pHead1;
32         while (pHead1!=NULL && pHead2!=NULL){
33             if (pHead1->val < pHead2->val){
34                 node->next=pHead1;
35                 node=node->next;
36                 pHead1=pHead1->next;
37             }
38             else{
39                 node->next=pHead2;
40                 node=node->next;
41                 pHead2=pHead2->next;
42             }
43         }
44         if (pHead1!=NULL){
45            node->next=pHead1;
46         }
47         else{
48             node->next=pHead2;
49         }
50         return Node;
51     }
52 };

 

posted @ 2020-07-22 18:48  生活待我如初恋  阅读(154)  评论(0编辑  收藏  举报