LeetCode-golang合并两个有序链表(题21)

题面

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

源码

type ListNode struct {
    Val int
    Next *ListNode
}
func A21_mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
    if l1==nil{
        return l2
    }
    if l2==nil {
        return l1
    }
    head:=ListNode{0,nil}
    p:=&ListNode{0,nil}
    head.Next=p
    l1value:=l1.Val;l2value:=l2.Val
    for {
        if l1value<l2value{
            p.Val=l1value
            p.Next=&ListNode{0,nil}
            p=p.Next
            if l1!=nil{
                l1=l1.Next
            }
        }else {
            p.Val=l2value
            p.Next=&ListNode{0,nil}
            p=p.Next
            if l2!=nil{
                l2=l2.Next
            }
        }
        if l1!=nil{
            l1value=l1.Val
        }else {
            for l2!=nil{
                p.Val=l2value
                l2=l2.Next
                if l2!=nil{
                    p.Next=&ListNode{0,nil}
                    p=p.Next
                }
            }
        }
        if l2!=nil{
            l2value=l2.Val
        }else {
            for l1!=nil{
                p.Val=l1value
                l1=l1.Next
                if l1!=nil{
                    p.Next=&ListNode{0,nil}
                    p=p.Next
                }
            }
        }
        if l1==nil&&l2==nil{
            break
        }
    }
    return head.Next
}

测试代码及结果

func TestA21_mergeTwoLists(t *testing.T) {
	l1:=question21_30.ListNode{1,nil}
	l1.Next=&question21_30.ListNode{2,nil}
	l1.Next.Next=&question21_30.ListNode{4,nil}

	l2:=question21_30.ListNode{1,nil}
	l2.Next=&question21_30.ListNode{3,nil}
	l2.Next.Next=&question21_30.ListNode{4,nil}
	result:=question21_30.A21_mergeTwoLists(&l1,&l2)
	var str string
	for result!=nil{
		str+=fmt.Sprintf("%d",result.Val)
		result=result.Next
	}
	fmt.Println(str)
}
=== RUN   TestA21_mergeTwoLists
112344
--- PASS: TestA21_mergeTwoLists (0.00s)
PASS

你可能感兴趣的:(LeetCode-golang合并两个有序链表(题21))