반응형
    
    
    
  https://leetcode.com/problems/merge-two-sorted-lists/
Merge Two Sorted Lists - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
linked list의 이해가 필요한 자료구조 문제였습니다.
📕 풀이방법
📔 입력 및 초기화
두 linked list의 원소들을 하나로 모으기 위해 vector vals와 ListNode *cur를 선언합니다.list1, list2를 cur를 이용해 순회하며 vector에 모든 원소를 담습니다.이후 오름차순으로 정렬해줍니다.
📔 풀이과정
vals의 크기가 0이라면 nullptr를 반환해줍니다.
아니라면 정답 ListNode *ans를 선언해 모든 원소를 담아줍니다.
📔 정답출력
ans를 반환합니다.
📕 Code
📔 C++
/**
 * 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 *cur = list1;
        vector <int> vals;
        while(cur != nullptr) {
            vals.push_back(cur->val);
            cur = cur->next;
        }
        cur = list2;
        while(cur != nullptr) {
            vals.push_back(cur->val);
            cur = cur->next;
        }
        
        if(!vals.size()) return nullptr;
        sort(vals.begin(), vals.end());
        
        ListNode *ans = new ListNode(vals[0]);
        cur = ans;
        for(int i = 1; i < vals.size(); i++) {
            ListNode *next = new ListNode(vals[i]);
            cur -> next = next;
            cur = cur->next;
        }
        return ans;
    }
};*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.
'Algorithm > 자료구조' 카테고리의 다른 글
| (C++) - LeetCode (easy) 94. Binary Tree Inorder Traversal (0) | 2022.11.14 | 
|---|---|
| (C++) - LeetCode (easy) 83. Remove Duplicates from Sorted List (0) | 2022.11.12 | 
| (C++) - LeetCode (easy) 20. Valid Parentheses (0) | 2022.10.18 | 
| (C++) - 백준(BOJ) 5157 : Bailout Bonus (0) | 2022.07.15 | 
| (C++) - 백준(BOJ) 15720 : 카우버거 (0) | 2022.06.01 |