leet-code/merge-two-sorted-lists/sol.go

34 lines
594 B
Go

package main
type ListNode struct {
Val int
Next *ListNode
}
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode {
next1, next2 := list1, list2
head := &ListNode{
Val: -1,
Next: nil,
}
current := head
for next1 != nil || next2 != nil {
if next2 == nil || (next1 != nil && next1.Val < next2.Val) {
current.Next = next1
next1 = next1.Next
} else {
current.Next = next2
next2 = next2.Next
}
current = current.Next
}
return head.Next
}