乐趣区

golang-链表合并

思路来源:

https://leetcode-cn.com/probl…

 将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。示例:输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
func main(){a := new(Node)
    a.Data = 1
    a.Next = &Node{2, &Node{4, nil}}

    b := new(Node)
    b.Data = 1
    b.Next = &Node{3, &Node{4, nil}}

    c := merge(a, b)
    for {fmt.Print(c.Data)
        if c.Next == nil {break}
        c = c.Next
    }
}

type Node struct {
    Data int
    Next *Node
}

func merge(a, b *Node) *Node {
    if a == nil {return b}
    if b == nil {return a}

    if a.Data < b.Data {a.Next = merge(a.Next, b)
        return a
    }
    b.Next = merge(a, b.Next)
    return b
}
退出移动版