forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
21-Merge-Two-Sorted-Lists go solution
- Loading branch information
dfad
committed
Sep 29, 2022
1 parent
2c65a33
commit fb03289
Showing
1 changed file
with
49 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |