1. 程式人生 > >21. 合並兩個有序鏈表

21. 合並兩個有序鏈表

src 拼接 節點 block 兩個 col 示例 研發 關註

知乎ID: 碼蹄疾
碼蹄疾,畢業於哈爾濱工業大學。
小米廣告第三代廣告引擎的設計者、開發者;
負責小米應用商店、日歷、開屏廣告業務線研發;
主導小米廣告引擎多個模塊重構;
關註推薦、搜索、廣告領域相關知識;

題目

將兩個有序鏈表合並為一個新的有序鏈表並返回。新鏈表是通過拼接給定的兩個鏈表的所有節點組成的。

示例:

輸入:1->2->4, 1->3->4
輸出:1->1->2->3->4->4

分析

有序鏈表合並,每次都取兩個中較小的一個,直到其中一個遍歷到鏈表結尾結束遍歷。
如果這時候還是剩下的元素,肯定比之前的元素都大,直接添加到鏈表結尾就好。

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; } ListNode merged = null; ListNode head = null; while (l1 != null && l2 != null) { if (head == null) { if (l1.val < l2.val) { merged = l1; l1 = l1.next; }
else { merged = l2; l2 = l2.next; } head = merged; continue; } if (l1.val < l2.val) { merged.next = l1; l1 = l1.next; } else { merged.next = l2; l2 = l2.next; } merged = merged.next; } while (l1 != null) { merged.next = l1; l1 = l1.next; merged = merged.next; } while (l2 != null) { merged.next = l2; l2 = l2.next; merged = merged.next; } return head; } }

技術分享圖片

21. 合並兩個有序鏈表