https://leetcode.com/problems/merge-two-sorted-lists/
연결리스트 (linked list) 문제를 처음 접해봐서
discuss 참고함
배열과의 차이점을 꼭 알아두고, 언제 활용해야될지 생각해야될듯..
package main
type ListNode struct {
Val int
Next *ListNode
}
func main() {
list1 := &ListNode{3, &ListNode{}}
list2 := &ListNode{2, &ListNode{}}
mergeTwoLists(list1, list2)
}
// 제출 코드
// discuss 참고
func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode {
var newList = &ListNode{}
var out = newList
for list1 != nil && list2 != nil {
if list1.Val < list2.Val {
newList.Next = list1
list1 = list1.Next
newList = newList.Next
} else {
newList.Next = list2
list2 = list2.Next
newList = newList.Next
}
}
if list1 != nil {
newList.Next = list1
} else if list2 != nil {
newList.Next = list2
}
return out.Next
}
'Algorithm > Go' 카테고리의 다른 글
[LeetCode] Longest Substring Without Repeating Characters (0) | 2022.01.03 |
---|---|
[LeetCode] Minimum Index Sum of Two Lists (0) | 2022.01.03 |
[LeetCode] Contains Duplicate (0) | 2021.12.26 |
[LeetCode] Rotate String (0) | 2021.12.20 |
[Leetcode] Single Number (0) | 2021.12.20 |