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.

将两个有序链表合二为一

Solution

逐次比较l1、l2,将较小的那个结点添加到新链表尾部,并指向下一个结点

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
    if l1 == nil {
        return l2
    } else if l2 == nil {
        return l1
    }

    var head, tail *ListNode

    // 将首次判断放在循环外,可以减少判断次数,提高效率
    if l1.Val < l2.Val {
        head = l1
        l1 = l1.Next
    } else {
        head = l2
        l2 = l2.Next
    }

    tail = head

    for {
        if l1 == nil {
            tail.Next = l2
            break
        } else if l2 == nil {
            tail.Next = l1
            break
        } else if l1.Val < l2.Val {
            tail.Next = l1
            tail = l1
            l1 = l1.Next
        } else {
            tail.Next = l2
            tail = l2
            l2 = l2.Next
        }
    }

    return head
}

Similar Problem