leetcode题目-合并两个有序链表
go语言实现(双指针法):
type ListNode struct {
Val int
Next *ListNode
}
func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode {
if list1 == nil {
return list2
}
if list2 == nil {
return list1
}
tmpNode1 := list1
tmpNode2 := list2
var head *ListNode = nil
if tmpNode1.Val <= tmpNode2.Val {
head = tmpNode1
tmpNode1 = tmpNode1.Next
} else {
head = tmpNode2
tmpNode2 = tmpNode2.Next
}
var current = head
for tmpNode1 != nil && tmpNode2 != nil {
if tmpNode1.Val <= tmpNode2.Val {
current.Next = tmpNode1
tmpNode1 = tmpNode1.Next
} else {
current.Next = tmpNode2
tmpNode2 = tmpNode2.Next
}
current = current.Next
}
if tmpNode1 != nil {
current.Next = tmpNode1
}
if tmpNode2 != nil {
current.Next = tmpNode2
}
return head
}