GO题解 | #合并有序链表#
来自
【GO题解】
552 浏览
0 回复
2021-04-21
合并有序链表
http://www.nowcoder.com/practice/a479a3f0c4554867b35356e0d57cf03d
go解题答案
- 思路概括:、归并方法
- 思路核心:
1、加节点就是next指到新节点func mergeTwoLists( l1 *ListNode , l2 *ListNode ) *ListNode {
// write code here
if l1==nil {
return l2
}
if l2==nil {
return l1
}
res:= &ListNode{Val:0}
head:=res
for l1 !=nil && l2 !=nil { // 2个链表都不为nil时大小
if l1.Val<l2.Val {
res.Next=l1
l1=l1.Next
}else{
res.Next=l2
l2=l2.Next
}
res= res.Next
}
if l1!=nil{ //只有一方有的时候把整个追加到后面
res.Next = l1
}else{
res.Next = l2
}
return head.Next
}
如果有帮助请点个赞哦, 更多文章请看我的博客
题主背景
- 从业8年——超级内卷500Q技术经理——目前专注go和微服务架构