关于go:Leetcode专题21合并两个有序链表

40次阅读

共计 351 个字符,预计需要花费 1 分钟才能阅读完成。

leetcode 链接:
https://leetcode.cn/problems/merge-two-sorted-lists/description/
解题思路:

func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {prehead := &ListNode{}
    result := prehead
    for l1 != nil && l2 != nil {
        if l1.Val < l2.Val {
            prehead.Next = l1
            l1 = l1.Next
        }else{
            prehead.Next = l2
            l2 = l2.Next
        }
        prehead = prehead.Next
    }
    if l1 != nil {prehead.Next = l1}
    if l2 != nil {prehead.Next = l2}
    return result.Next
}

正文完
 0