图解算法——合并两个有序的列表(Merge Two Sorted Lists)

1. 题目描述

Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists.

2.示例

示例1:

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

示例2:

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

示例3:

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

3. 要求

  • The number of nodes in both lists is in the range [0, 50].
  • -100 <= Node.val <= 100
  • Both l1 and l2 are sorted in non-decreasing order.

4.解题思想

和上篇博客 图解算法——合并k个排序列表(Merge k Sorted Lists) 类似,

/**
 * 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){
        ListNode head = new ListNode(0);
        ListNode res = head;
        while(l1 != null && l2!=null){
            //res.val = l1.val>l2.val?l2.val:l1.val;
            if(l1.val>=l2.val){
                //res.val = l2.val;
                res.next = l1;//是res.next而不是赋值操作.val
          l2
= l2.next; }else if(l1.val<l2.val){ //res.val = l1.val; res.next = l2;
          l1
= l1.next; } res = res.next; } if(l1 != null){ res.next = l1;//这里是res.next,不是res } if(l2 != null){ res.next = l2;//这里是res.next,不是res } return head.next;//因为初始化时候设置初始节点为0,l1和l2的节点从第二个开始 } //递归 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; } } }

Over......

原文地址:https://www.cnblogs.com/gjmhome/p/14412308.html