February 24, 2020
使用语言:Go
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
if l1 == nil {
return l2
}
if l2 == nil {
return l1
}
var res *ListNode
if l1.Val < l2.Val {
res = &ListNode{
Val: l1.Val,
}
l1 = l1.Next
} else {
res = &ListNode{
Val: l2.Val,
}
l2 = l2.Next
}
head := res
for l1 != nil && l2 != nil {
if l1.Val < l2.Val {
res.Next = &ListNode{
Val: l1.Val,
}
l1 = l1.Next
} else {
res.Next = &ListNode{
Val: l2.Val,
}
l2 = l2.Next
}
res = res.Next
}
if l1 == nil {
res.Next = l2
} else {
res.Next = l1
}
return head
}
要合并两个链表,必然要遍历两个链表,同时作比较。线性的办法就是同时遍历两个链表,根据值的大小判断哪个链表往后走。
痕迹
没有过去,就没法认定现在的自己