Likou linked list questions: 21 merge two ordered linked lists

topic

Insert picture description here

My initial thoughts and problems

When I first solved the problem, I thought of a recursive solution, but there was an oversight that did not distinguish between l1.val and l1.next during the encoding process, so you should pay attention to the subsequent encoding. See the recursive problem solution below for details.

Problem solving method one: recursion

Summarize some recursive three steps before doing the problem:
(1) Solve the basic problem
(2) How to turn a big problem into a small problem
(3) How to turn a solution to a small problem into a solution to a big problem

Insert picture description hereCode:


class Solution {
    
    
    public ListNode mergeTwoLists(ListNode l1, 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(l2.next, l1);
            return l2;
        }

    }
}

Note that when comparing sizes, l1.val is compared with l2val.
l1.next = mergeTwoLists(l1.next, l2) The parameter in the method is l1.next, not l1.val.

Time complexity and space complexity:
Insert picture description here

Problem solving method 2: iteration

Guess you like

Origin blog.csdn.net/ambitionLlll/article/details/113920703