21. Merge Two Sorted Lists

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.

一刷
题解:合并两个排序的单链表, 创建一个dummy head,然后进行合并。 Time Complexity - O(n),Space Complexity - O(1)。

public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode res = new ListNode(-1);
        ListNode header = res;
        while(l1!=null && l2!=null){
            if(l1.val <= l2.val){
                res.next = l1;
                res = res.next;
                l1 = l1.next;
            }
            else{
                res.next = l2;
                res = res.next;
                l2 = l2.next;
            }
        }
        
        while(l1!=null){
            res.next = l1;
            res = res.next;
            l1 = l1.next;
        }
        
        while(l2!=null){
            res.next = l2;
            res = res.next;
            l2 = l2.next;
        }
        
        return header.next;
    }
}

二刷:
思路很简单,每次取l1, l2中较小的值作为下一个node, 注意dummy node的使用

/**
 * 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) {
        ListNode dummy = new ListNode(-1);
        ListNode cur = dummy;
        while(l1!=null && l2!=null){
            if(l1.val < l2.val){
                cur.next = new ListNode(l1.val); 
                l1 = l1.next;
            }
            else{
                cur.next = new ListNode(l2.val);
                l2 = l2.next;
            }
            cur = cur.next;
        }
        
        while(l1!=null){
            cur.next = l1;
            l1 = l1.next;
            cur = cur.next;
        }
        
        while(l2!=null){
            cur.next = l2;
            l2 = l2.next;
            cur = cur.next;
        }
        
        return dummy.next;
        
    }
}

你可能感兴趣的:(21. Merge Two Sorted Lists)