> For the complete documentation index, see [llms.txt](https://pachirisu.gitbook.io/leetcode-algorithms/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://pachirisu.gitbook.io/leetcode-algorithms/21.-merge-two-sorted-lists.md).

# 21. Merge Two Sorted Lists

## Problem

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.

Example:

```
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
```

**Related Topics:**

`Linked List`

## Analysis

方法一：递归。

方法二：非递归，设置节点，跟踪判断、更新。

## Code

**递归**

```kotlin
/**
 * Definition for singly-linked list.
 * class ListNode(var `val`: Int = 0) {
 *     var next: ListNode? = null
 * }
 */
class Solution {

    fun mergeTwoLists(l1: ListNode?, l2: ListNode?): ListNode? {

        return when {
            l1 == null -> l2
            l2 == null -> l1
            l1.`val` < l2.`val` -> {
                l1.next = mergeTwoLists(l1.next, l2)
                l1
            }
            else -> {
                l2.next = mergeTwoLists(l1, l2.next)
                l2
            }
        }
    }
}
```

**非递归**

```kotlin
/**
 * Definition for singly-linked list.
 * class ListNode(var `val`: Int = 0) {
 *     var next: ListNode? = null
 * }
 */
class Solution {

    fun mergeTwoLists(l1: ListNode?, l2: ListNode?): ListNode? {

        val head = ListNode(0)
        var main = head
        var left = l1
        var right = l2

        loop@ while (true) {
            when {
                left == null -> {
                    main.next = right
                    break@loop
                }
                right == null -> {
                    main.next = left
                    break@loop
                }
                left.`val` < right.`val` -> {
                    main.next = left
                    left = left.next
                }
                else -> {
                    main.next = right
                    right = right.next
                }
            }
            main = main.next!!
        }

        return head.next
    }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://pachirisu.gitbook.io/leetcode-algorithms/21.-merge-two-sorted-lists.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
