Skip to content

Latest commit

 

History

History

0021.merge-two-sorted-lists

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 

题目描述

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 

 

示例:

输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4 

解题思路

代码实现

Golang 1

funcmergeTwoLists1(l1*ListNode, l2*ListNode) *ListNode { ifl1==nil { returnl2 } ifl2==nil { returnl1 } ret:=&ListNode{} ifl1.Val<=l2.Val { ret=l1ret.Next=mergeTwoLists1(l1.Next, l2) } else { ret=l2ret.Next=mergeTwoLists1(l1, l2.Next) } returnret }

Golang 2

funcmergeTwoLists2(l1*ListNode, l2*ListNode) *ListNode { head:=&ListNode{} ret:=headforl1!=nil&&l2!=nil { ifl1.Val<l2.Val { ret.Next=l1l1=l1.Next } else { ret.Next=l2l2=l2.Next } ret=ret.Next } ifl1!=nil { ret.Next=l1 } ifl2!=nil { ret.Next=l2 } returnhead.Next }
close