짱아의 개발 기록장

LeetCode : 21. Merge Two Sorted Lists 본문

Algorithm/LeetCode

LeetCode : 21. Merge Two Sorted Lists

jungahshin 2021. 1. 20. 13:33
반응형

LeetCode에서 전에 이런 문제를 풀었던 기억이?...

Merge Sort을 할때에 두 개로 나눈 배열을 합병하는 과정을 그대로 구현하면 된다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        // int idx = 0;
        ListNode* dummy = new ListNode();
        ListNode* curr = dummy;
        if(l1==NULL || l2==NULL){
            if(l1==NULL){
                return l2;
            }else{
                return l1;
            }
        }
        
        while(l1!=NULL || l2!=NULL){
            if(l1!=NULL && l2!=NULL){
                if((l1->val)<(l2->val)){
                    curr->val = l1->val;
                    l1 = l1->next;
                }else{
                    curr->val = l2->val;
                    l2 = l2->next;
                }                
            }else{
                if(l1!=NULL){
                    curr->val = l1->val;
                    l1 = l1->next;
                }else{
                    curr->val = l2->val;
                    l2 = l2->next;
                }
            }
 
            if(l1==NULL && l2==NULL){
                break;
            }
            
            curr->next = new ListNode();
            curr = curr->next;
        }
        
        return dummy;
    }
};
cs
반응형

'Algorithm > LeetCode' 카테고리의 다른 글

LeetCode : 111. Minimum Depth of Binary Tree  (0) 2021.01.21
LeetCode : 2. Add Two Numbers  (0) 2021.01.20
LeetCode : 49. Group Anagrams  (0) 2021.01.19
LeetCode : 20. Valid Parentheses  (0) 2021.01.19
LeetCode : 77. Combinations  (0) 2021.01.18
Comments