class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
ListNode* head = new ListNode();
ListNode* point = new ListNode();
// for head
if (list1 or list2) {
if (list1 and list2) {
if (list1->val < list2->val) {
head->next = list1;
point->next = list1;
list1 = list1->next;
}
else {
head->next = list2;
point->next = list2;
list2 = list2->next;
}
}
else if (list1) {
return list1;
}
else {
return list2;
}
}
// solve
while (list1 or list2) {
if (list1 and list2) {
if (list1->val < list2->val) {
point->next->next = list1;
point->next = list1;
list1 = list1->next;
}
else {
point->next->next = list2;
point->next = list2;
list2 = list2->next;
}
}
else if (list1) {
point->next->next = list1;
break;
}
else {
point->next->next = list2;
break;
}
}
return head->next;
}
};
|
cs |
풀이:
1. 시작점인 head를 저장해 줍니다.
2. point->next를 이용하여 노드의 방향을 조절합니다.
'Leetcode' 카테고리의 다른 글
LeetCode 1114. Print in Order [C++/ atomic] (0) | 2022.06.03 |
---|---|
LeetCode 1114. Print in Order [C++/ promise] (0) | 2022.06.03 |
Remove Nth Node From End of List, LeetCode, c++/cpp/c (0) | 2022.06.01 |
leetcode Reverse Integer (0) | 2022.05.29 |
Add Two Numbers leetcode 2 (0) | 2022.05.29 |