# 21.Merge-Two-Sorted-Lists

## 21. Merge Two Sorted Lists

## 题目地址

<https://www.lintcode.com/problem/merge-two-sorted-lists>

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

## 题目描述

```
Merge two sorted (ascending) linked lists and return it as a new sorted list. The new sorted list should be made by splicing together the nodes of the two lists and sorted in ascending order.
```

## 代码

### Approach 1: Iteration

**Intuition**

We can achieve the same idea via iteration by assuming that `l1` is entirely less than `l2` and processing the elements one-by-one, inserting elements of `l2` in the necessary places in `l1`.

**Complexity Analysis**

* Time complexity : O(n + m)
* Space complexity : O(1)

```java
public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    ListNode dummy = new ListNode(0);
    ListNode curr = dummy;

    while (l1 != null && l2 != null) {
      if (l1.val > l2.val){
        curr.next = l2;
        l2 = l2.next;
      } else {
        curr.next = l1;
        l1 = l1.next;
      }

      curr = curr.next;
    }

    curr.next = (l1 != null) ? l1 : l2;

    return dummy.next;
  }
}
```

### Approach 2: Recursion

**Intuition**

We can recursively define the result of a `merge` operation on two lists as the following (avoiding the corner case logic surrounding empty lists):

list1.next = merge(list1.next, list2) list1.val < list2.val

list2.next = merge(list1, list2.next) otherwise

Namely, the smaller of the two lists' heads plus the result of a `merge` on the rest of the elements.

**Complexity Analysis**

* Time complexity : O(n + m)
* Space complexity : O(n + m)

  The first call to `mergeTwoLists` does not return until the ends of both `l1` and `l2` have been reached, so n + m stack frames consume O(n + m)space.

```java
class Solution {
  public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    if (l1 == null) {
      return l2;
    } else if (l2 == null) {
      return l1;
    } else if (l1.val < l2.val) {
      l1.next = mergeTwoLists(l1.next, l2);
      return l1;
    } else {
      l2.next = mergeTwoLists(l1, l2.next);
      return l2;
    }
  }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wentao-shao.gitbook.io/leetcode/linked-list/21.merge-two-sorted-lists.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
