Created
January 21, 2022 04:37
-
-
Save CollinShoop/a71d95891853f6d8d287f3aea5d9dd7c to your computer and use it in GitHub Desktop.
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
/** | |
* Definition for singly-linked list. | |
* type ListNode struct { | |
* Val int | |
* Next *ListNode | |
* } | |
*/ | |
func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode { | |
if list1 == nil { | |
return list2 | |
} | |
if list2 == nil { | |
return list1 | |
} | |
// find the head | |
var head *ListNode | |
if list1.Val < list2.Val { | |
head = list1 | |
list1 = list1.Next | |
} else { | |
head = list2 | |
list2 = list2.Next | |
} | |
// keep track of the start to return later | |
start := head | |
// iterate 1 head at a time, appending to head node | |
for list1 != nil || list2 != nil { | |
if list1 != nil { | |
if list2 == nil || list1.Val < list2.Val { | |
head.Next = list1 | |
list1 = list1.Next | |
} else { | |
head.Next = list2 | |
list2 = list2.Next | |
} | |
} else if list2 != nil { | |
if list1 == nil || list2.Val < list1.Val { | |
head.Next = list2 | |
list2 = list2.Next | |
} else { | |
head.Next = list1 | |
list1 = list1.Next | |
} | |
} | |
head = head.Next | |
} | |
return start | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment