Skip to content

Commit 94011da

Browse files
committed
solve : merge-two-sorted-lists
1 parent cca0cfd commit 94011da

File tree

1 file changed

+39
-1
lines changed

1 file changed

+39
-1
lines changed

merge-two-sorted-lists/mkwkw.cpp

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,39 @@
1-
//set-up
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode() : val(0), next(nullptr) {}
7+
* ListNode(int x) : val(x), next(nullptr) {}
8+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
9+
* };
10+
*/
11+
//풀이 참고하였음.
12+
class Solution {
13+
public:
14+
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { //list1, list2 다 포인터
15+
ListNode mergedNode(-1); //mergedNode 객체 선언
16+
ListNode* mergedNodeList = &mergedNode; //node: (merged 객체)의 (주소) (&merged)저장 (객체를 포인터에 넣기)
17+
18+
ListNode* l1 = list1; // 포인터 l1
19+
ListNode* l2 = list2; // 포인터 l2
20+
21+
while (l1 != nullptr && l2 != nullptr) {
22+
//l1, l2 둘 중에 head 값(->val) 값이 작은 것을 node->next에 연결
23+
if (l1->val < l2->val) { // 포인터로 객체의 속성 참조(->)
24+
mergedNodeList->next = l1;
25+
l1 = l1->next;
26+
} else {
27+
mergedNodeList->next = l2;
28+
l2 = l2->next;
29+
}
30+
mergedNodeList = mergedNodeList->next;
31+
}
32+
33+
//남아있는 list를 node->next에 연결
34+
mergedNodeList->next = (l1 != nullptr) ? l1 : l2;
35+
//return the head of the merged linked list (mergeNode -1 다음 것을 가리키는 포인터 next)
36+
return mergedNode.next;
37+
38+
}
39+
};

0 commit comments

Comments
 (0)