A classic algorithmic problem: merge two ordered linked lists

I just scribbled this question on Leetcode, so I remembered a classic saying: People can't even do simple questions when they are extremely angry!

The difficulty of this question marked on Leetcode is a simple question, but after thinking about it for a long time, it was painful and I didn't know what was going on. In the end, it took me more than an hour to think about it. It was basically a recursive method, combined with a linked list, so it seemed a little simple, haha!

Ideas:

 

answer:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
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(l1,l2.next);
            return l2;
        }
    }
}

 

 

 

Guess you like

Origin blog.csdn.net/qq_36428821/article/details/112725912