1. 程式人生 > >LeedCode【021】【MergeTwoSortedLists】

LeedCode【021】【MergeTwoSortedLists】

一、原題要求:

將兩個有序連結串列合併為一個新的有序連結串列並返回。新連結串列是通過拼接給定的兩個連結串列的所有節點組成的。 

示例:

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

解題思路
* 使用頭結點root進行輔助操作,建立一個頭結點,再使用兩個引用指向兩個連結串列的頭結點,
* 將較小的結點值的結點摘下來接到root連結串列的末尾,同時被摘的鏈頭引用移動到下一個結點,
* 一直操作,到到原先兩個連結串列中有一個為空,最後再將剩下的結點接到root連結串列的末尾。
* 最後返回root的下一個結點,其就為新的連結串列頭。

二、程式碼實現:

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
        val = x;
        next = null;
    }
}

public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null && l2 == null) {
            return null;
        }
        ListNode old = new ListNode(0);
        ListNode head = old;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                head.next = l1;
                l1 = l1.next;
                head = head.next;
            } else {
                head.next = l2;
                l2 = l2.next;
                head = head.next;
            }
        }
        if (l1 == null) { // l1為空的時候,有可能l2不為空,所以把剩下的l1連結
            head.next = l2;
        }
        if (l2 == null) {// l2為空的時候,有可能l1不為空,所以把剩下的l2連結
            head.next = l1;
        }
        return old.next;
    }
}