Merge Two Sorted Lists

https://leetcode.com/problems/merge-two-sorted-lists/description/

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.

Thoughts

思路比较容易想,两个指针,那个指针指向的小就把它插入,再把指针往后移动。肯定会有一个先被插完,所以需要再对剩余的没插完的做处理。

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

Analysis

做题耗时7min

时间复杂度O(m + n)

Last updated