1. 程式人生 > >LeetCode—21. Merge Two Sorted Lists

LeetCode—21. Merge Two Sorted Lists

LeetCode—21. Merge Two Sorted Lists

題目

兩個有序連結串列,合併成一個。題目裡有一句話我沒理解好,她說“The new list should be made by splicing together the nodes of the first two 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) {
        if (l1 == null && l2 == null) {
            return null;
        }
        if(l1 == null) return l2;
        if(l2 == null) return l1;
        ListNode res = new ListNode(0);
        ListNode pre = res;
        while(l1!=null && l2!=null){
            if(l1.val<=l2.val){
                pre.next = l1;
                l1 = l1.next;
            }else{
                pre.next = l2;
                l2 = l2.next;
            }
            pre = pre.next;
        }
        if(l1!=null){
            pre.next = l1;
        }
        if(l2!=null){
            pre.next = l2;
        }
        return res.next;
    }
}