21. 合并两个排序链表(Merge Two Sorted Lists)

Title: 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.

Example:

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

Difficulty:

Easy

Implement Programming Language:

Go

Answer:

这道题为了代码的优雅,我就直接定义一个新的链表,来逐个存储了。虽然有O(n)的空间复杂度,但是忽略吧。

代码:

func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
    res := ListNode{}
    temp := &res
    for l1 != nil || l2 != nil{
        if l1 == nil{
            temp.Next = l2
            break
        }
        if l2 == nil{
            temp.Next = l1
            break
        }
        if l1.Val < l2.Val{
            temp.Next = l1
            l1 = l1.Next
        }else{
            temp.Next = l2
            l2= l2.Next
        }
        temp = temp.Next
    }
    return res.Next
}

你可能感兴趣的:(21. 合并两个排序链表(Merge Two Sorted Lists))