LeetCode fifth day 21. Merge two ordered linked lists

The LeetCode 100-day foundation building series is mainly for practicing basic data structures and algorithms. The question bank is all LeetCode simple questions (medium and difficult questions will be updated in other series later), mainly written in C language and Java, and the previous questions can be completed. For the purpose of function, better algorithms and optimized code blocks will be used later.

  1. Merge two sorted lists
    insert image description here

Merges two ascending lists into a new ascending list and returns. The new linked list is formed by splicing all the nodes of the given two linked lists.
Example 1:

Input: l1 = [1,2,4], l2 = [1,3,4]
Output: [1,1,2,3,4,4]

Example 2:

Input: l1 = [], l2 = []
Output: []

Example 3:

Input: l1 = [], l2 = [0]
Output: [0]
C language:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
    
    
    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;
    }
}

Problem-solving ideas: The termination condition is that when one of the two linked lists is NULL, the other linked list is returned directly. The
recursive method is to judge the size of the l1 and l2 head nodes, and then point the smaller next to the merged result of the remaining nodes.
Specifically, put the first number in the first column into the first number in the linked list, compare the second number in the first column with the first number in the second example, put the smaller one into the second place in the linked list, and then Compare until all the numbers in the first or second column are entered into the linked list which is empty at this point.
Java:

class Solution {
    
    
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    
    
        if (l1 == null) {
    
    
            return l2;
        } else if (l2 == null) {
    
    
            return l1;
        } else 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 blog.csdn.net/qq_43310387/article/details/123965963