圖解算法——合並兩個有序的列表(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......

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM