[Simple Algorithm] 23. Merge two ordered linked lists

topic:

Merge two sorted linked lists into a new sorted linked list and return. The new linked list is formed by splicing all the nodes of the given two linked lists.

Example:

Input: 1 -> 2 -> 4 , 1 -> 3 -> 4 
Output: 1 -> 1 -> 2 -> 3 -> 4 -> 4

Problem solving ideas:

1. Recursion:

Add smaller elements in turn to the new link.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        if(l1 == NULL){
            return l2;
        }
        
        if(l2 == NULL){
            return l1;
        }
        
        if(l1->val >= l2->val){
            l2->next = mergeTwoLists(l1,l2->next);
            return l2;
        }else{
            l1->next = mergeTwoLists(l1->next,l2);
            return l1;
        }
    }
};

Non-recursive:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
/*
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode * p1 = l1;
        ListNode * p2 = l2;
        ListNode * res = NULL;
        ListNode * cur = NULL;
        
        if(p1 == NULL){
            return p2;
        }
        if(p2 == NULL){
            return p1;
        }
        
        while(p1&&p2){
            ListNode * next = NULL;
            if(p1->val > p2->val){
                next = p2;
                p2 = p2->next;
            }else{
                next = p1;
                p1 = p1->next;
            }
            
            if(res == NULL){
                res = next;
                cur = next;
            }else{
                cur->next = next;
                cur = next;
            }
        }
        
        if(p1){
            cur->next = p1;
        }
        
        if(p2){
            cur->next = p2;
        }
        
        return res;
    }
};
*/
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        if(l1 == NULL && l2 == NULL){
            return NULL;
        }
        
        if(l1 == NULL){
            return l2;
        }
        
        if(l2 == NULL){
            return l1;
        }
        
        if(l1->val < l2->val){
            l1->next = mergeTwoLists(l1->next,l2);
            return l1;
        }else{
            l2->next = mergeTwoLists(l1,l2->next);
            return l2;
        }
    }
};

 

Guess you like

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