17 Merge two sorted linked lists

Input two monotonically increasing linked lists, and output the linked list after combining the two linked lists. Of course, we need the combined linked list to satisfy the monotonically non-decreasing rule.

 

 

C++: Iteration

 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)
14             return pHead2 ;
15         if (pHead2 == NULL)
16             return pHead1 ;
17         ListNode* pHead = NULL ;
18         if (pHead1->val <= pHead2->val){
19             pHead = pHead1 ;
20             pHead1 = pHead1->next ;
21         }else{
22             pHead = pHead2 ;
23             pHead2 = pHead2->next ;
24         }
25         ListNode* p = pHead ;
26         while(pHead1 != NULL && pHead2 != NULL){
27             if (pHead1->val <= pHead2->val){
28                 p->next = pHead1 ;
29                 pHead1 = pHead1->next ;
30             }else{
31                 p->next = pHead2 ;
32                 pHead2 = pHead2->next ;
33             }
34             p = p->next ;
35         }
36         if (pHead1 != NULL)  p->next = pHead1 ;
37         if (pHead2 != NULL)  p->next = pHead2 ;
38         return pHead ;
39     }
40 };

 

 

C++: recursion

 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)
14             return pHead2 ;
15         if (pHead2 == NULL)
16             return pHead1 ;
17         if (pHead1->val <= pHead2->val){
18             pHead1->next = Merge(pHead1->next , pHead2) ;
19             return pHead1 ;
20         }else{
21             pHead2->next = Merge(pHead1 , pHead2->next) ;
22             return pHead2 ;
23         }
24     }
25 };

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324848859&siteId=291194637