728x90
반응형
https://leetcode.com/problems/merge-two-sorted-lists/description/
문제
문제 분석
- list1과 list2의 각 요소들을 하나씩 비교해서 작은 것들을 먼저 결과에 넣습니다. 그 다음에 남은 리스트가 있다면 통째로 연결합니다.
풀이
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
ListNode dummy;
ListNode* tail = &dummy;
while (list1 && list2) {
if (list1->val <= list2->val) {
tail->next = list1;
list1 = list1->next;
} else {
tail->next = list2;
list2 = list2->next;
}
tail = tail->next;
}
tail->next = list1 ? list1 : list2;
return dummy.next;
}
};
728x90
반응형
'Problem Solving > LeetCode' 카테고리의 다른 글
[LeetCode] C++ 2. Add Two Numbers (0) | 2024.08.17 |
---|---|
[LeetCode] C++ 206. Reverse Linked List (0) | 2024.08.16 |
[LeetCode] C++ 234. Palindrome Linked List (0) | 2024.08.16 |
[LeetCode] C++ 121. Best Time to Buy and Sell Stock (0) | 2024.08.16 |
[LeetCode] C++ 238. Product of Array Except Self (0) | 2024.08.16 |