Skip to content

Commit

Permalink
21-Merge-Two-Sorted-Lists go solution
Browse files Browse the repository at this point in the history
  • Loading branch information
dfad committed Sep 29, 2022
1 parent 2c65a33 commit fb03289
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions go/21-Merge-Two-Sorted-Lists.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/**
* 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
}

ptr1, ptr2 := l1, l2

result := new(ListNode)

temp := result

for ptr1 != nil && ptr2 != nil {
if ptr1.Val < ptr2.Val {
temp.Next = ptr1
temp = temp.Next
ptr1 = ptr1.Next
} else {
temp.Next = ptr2
temp = temp.Next
ptr2 = ptr2.Next
}
}

for ptr1 != nil{
temp.Next = ptr1
temp = temp.Next
ptr1 = ptr1.Next
}

for ptr2 != nil{
temp.Next = ptr2
temp = temp.Next
ptr2 = ptr2.Next
}

result = result.Next
return result
}

0 comments on commit fb03289

Please sign in to comment.