Golang linked list merge

Posted May 28, 20201 min read

Source of ideas:

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

Combine the two ascending linked lists into a new ascending linked list and return. The new linked list is composed of all the nodes of the given two linked lists.

Examples:

Input:1-> 2-> 4, 1-> 3-> 4
Output: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
}