21. Merge Two Sorted Lists

158 阅读1分钟

题目描述

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

解题思路

链表的基本操作, 使用临时指针, 然后遍历 2 个链表

示例代码

func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {

    var p1 = l1
    var p2 = l2

    let head = ListNode(0)
    var tail = head

    while p1 != nil && p2 != nil {

        if p1!.val > p2!.val {
            tail.next = p2!
            p2 = p2!.next
        }else {
            tail.next = p1!
            p1 = p1!.next
        }
        tail = tail.next!
    }
    tail.next = p1 ?? p2
    return head.next
}