[LeetCode] 21 - Merge Two Sorted Lists
문제
- 링크: https://leetcode.com/problems/merge-two-sorted-lists
- 난이도: Easy
- 태그: 링크드 리스트, 재귀
- 결과:
Time: 0 ms (100%), Space: 19.35 MB (86.77%)
풀이
/**
* 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; // head 초기화의 복잡성을 낮추기 위한 더미노드
ListNode* tail = &dummy;
while (list1 != nullptr && list2 != nullptr)
{
if (list1->val < list2->val)
{
tail->next = list1;
list1 = list1->next;
}
else
{
tail->next = list2;
list2 = list2->next;
}
tail = tail->next;
}
tail->next = (list1 == nullptr) ? list2 : list1;
return dummy.next;
}
}
;
이미 정렬되어 있으니 연결만 잘 해주면 되는 문제다. 원래는 더미 노드를 만들지 않으려고 했는데, 동적할당하는 코드밖에 생각나지 않아서였다. 그래서 초기화 관련 코드가 꽤 길어졌는데, 일단 제출 후 AI와 다듬어보는 과정에서 그냥 지역변수로 선언하면 된다는 걸 알게 됐다.
배운 점과 후기
지역변수에 더미 노드를 선언해서 주소를 넘기면 되는거였는데… 생각에 갇히지 말자!
댓글남기기