美文网首页LeetCode By Go
[LeetCode By Go 80]21. Merge Two

[LeetCode By Go 80]21. Merge Two

作者: miltonsun | 来源:发表于2017-09-01 11:05 被阅读14次

    题目

    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.

    解题思路

    新建一个链表l3,遍历l1,l2, 每次比较l1,l2中第一个节点大小,选择较小的元素放入l3的末尾

    1. 先找到l1,l2中第一个较小的元素,作为l3第一个元素
    2. 遍历l1,l2,将其中元素插入l3末尾,直到l1,l2中有一个链表遍历完
    3. 如果l1为空,则将l2剩余元素放到l3末尾;如果l2为空,则将l1剩余元素放到l3末尾

    代码

    /**
     * Definition for singly-linked list.
     * type ListNode struct {
     *     Val int
     *     Next *ListNode
     * }
     */
    func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
        if nil == l1 {
            return l2
        }
        if nil == l2 {
            return l1
        }
    
        var p3 *ListNode
        p1, p2 := l1, l2
        if p1.Val < p2.Val {
            p3 = p1
            p1 = p1.Next
            p3.Next = nil
        } else {
            p3 = p2
            p2 = p2.Next
            p3.Next = nil
        }
        l3 := p3
    
        for ;p1 != nil && p2 != nil; {
            if p1.Val < p2.Val {
                tmp := p1
                p1 = p1.Next
                p3.Next = tmp
                p3 = p3.Next
                p3.Next = nil
            } else {
                tmp := p2
                p2 = p2.Next
                p3.Next = tmp
                p3 = p3.Next
                p3.Next = nil
            }
        }
        
        if p1 != nil {
            p3.Next = p1 
        } else {
            p3.Next = p2
        }
        return l3
    }
    

    相关文章

      网友评论

        本文标题:[LeetCode By Go 80]21. Merge Two

        本文链接:https://www.haomeiwen.com/subject/hgmhjxtx.html