[LeetCode] 21. Merging two sorted linked list (recursively)

topic

The two ordered lists into a new sorted list and return. The new list is by all nodes in a given mosaic composed of two lists. 

Example:

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

Source: stay button (LeetCode)
link: https://leetcode-cn.com/problems/merge-two-sorted-lists
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

Solution to a problem (rpm)

Recursive three elements:

  • Termination condition: two are named list l1 and l2, when the end l2 l1 is empty or empty
  • Returns: Each layer calls return the sorted list head
  • This recursion level content: if the value of the val l1 is smaller, then l1.next contact with the sorted list head, l2 empathy

A good illustration reference links: https://leetcode-cn.com/problems/merge-two-sorted-lists/solution/hua-jie-suan-fa-21-he-bing-liang-ge-you-xu -lian-bi /

Code

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

Guess you like

Origin www.cnblogs.com/coding-gaga/p/11823143.html