Skip to content

Commit

Permalink
Merge pull request neetcode-gh#1197 from razer96/21-Merge-Two-Sorted-…
Browse files Browse the repository at this point in the history
…Lists.go

21-Merge-Two-Sorted-Lists go solution
  • Loading branch information
dissesmac authored Sep 29, 2022
2 parents 6ee7152 + fb03289 commit b62784a
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 b62784a

Please sign in to comment.