21. Merge Two Sorted Lists

**Description**Hints**Submissions**Solutions

Total Accepted: 221656
Total Submissions: 571422
Difficulty: Easy
Contributor: LeetCode

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

Hide Company Tags
Amazon LinkedIn Apple Microsoft
Hide Tags
Linked List
Hide Similar Problems
(H) Merge k Sorted Lists (E) Merge Sorted Array (M) Sort List (M) Shortest Word Distance II

** 解題思路**
recursive 遞歸解法。 類似merge two sorted array

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
      // use recursive 
      if (l2 == null)  return l1;
      if (l1 == null)  return l2;
      
      ListNode mergeHead;
      
      if (l1.val < l2.val) {
          mergeHead = l1;
          mergeHead.next = mergeTwoLists(l1.next, l2);
      } else {
          mergeHead = l2;
          mergeHead.next = mergeTwoLists(l1, l2.next);
      }
      return mergeHead;
    }
    
    public ListNode mergeTwoListsFailed(ListNode l1, ListNode l2) {
        ListNode p1 = l1;
        ListNode p2 = l2 ;
        ListNode p = new ListNode(0);
        
        
        while (p1 != null && p2 != null) {
            // p.next = (p1.val > p2.val) ? new ListNode(p1.val) : new ListNode(p2.val);
            if (p1.val > p2.val) {
                p.next = new ListNode(p1.val);
                p1 = p1.next;
            } else {
                p.next = new ListNode(p2.val);
                p2 = p2.next;
            }
         
        }
        
        while (p2 != null) {
          p.next = new ListNode(p2.val);
          p2 = p2.next;
         
        }
        
        while (p1 != null) {
            p.next = new ListNode(p1.val);
            p1 = p1.next;
          
        }
        return p;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容