My Golang solution using goroutine and channel


  • 0
    C

    The idea is the same, but using the Go way.

    // merge_two_sorted_lists.go
    func MergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
    
    var ret,last *ListNode
    min := make(chan *ListNode) // unbuffered channel
    go func(){
        defer close(min) // close the channel in the end
        for {
            if l1 == nil {
                min <- l2
                return
            }
            if l2 == nil {
                min <- l1
                return 
            }
            if l1.Val < l2.Val {
                min <- l1
                l1 = l1.Next
           }else {
               min <- l2
               l2 = l2.Next
           }
        }
    }()
    
    // consume the channel
    for v := range min {
        if last != nil {
            last.Next = v
        }
        if ret == nil {
            ret = v
        }
        last = v
    }
    
    return ret
    }
    

    And the related test file is :

    // merge_two_sorted_lists_test.go
    type res struct {
        l1 *ListNode
        l2 *ListNode
        expect *ListNode
    }
    func TestMergeTwoLists(t *testing.T) {
        cases := []res{
            res{nil,nil,nil},
            res{nil,buildWithSlice([]int{5}),buildWithSlice([]int{5})},
            res{buildWithSlice([]int{1,4,6}), buildWithSlice([]int{3,5}),buildWithSlice([]int{1,3,4,5,6})},
        }
        for _, c := range cases {
            ret := MergeTwoLists(c.l1, c.l2)
            if !reflect.DeepEqual(ret, c.expect) {
                 t.Errorf("Expected %v, but got %v, with inputs (%v,%v)",c.expect, ret, c.l1, c.l2)
            }
        }
        t.Log("Passed")
    }
       
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.