Leetcode
[Leetcode] 148. Sort List
맑은 눈의 우사미
2023. 5. 19. 16:17
반응형
1. 문제링크
Sort List - LeetCode
Can you solve this real interview question? Sort List - Given the head of a linked list, return the list after sorting it in ascending order. Example 1: [https://assets.leetcode.com/uploads/2020/09/14/sort_list_1.jpg] Input: head = [4,2,1,3] Output: [1,
leetcode.com
지맘대로 생긴 ListNode를 오름차순으로 정렬하는 문제
2. Key Point - 제일 미니한 단위로 쪼갠다(재귀호출), merge한다
1) ListNode를 두개로 나눈다 - slow, fast pointers 사용
original = [4,2,3,1] 이라면
slow = [4,2], fast = [3,1]이 되도록 나눈다
이렇게 나눈 것을 재귀 호출하여 나눌 수 있는 가장 작은 2개의 ListNode로 만든다
2) merge 함수 구현 - 오름차순 정렬
나눈 2개의 ListNode를 ascending order로 merge한다
3. solution
class Solution {
public:
ListNode* merge(ListNode* l1, ListNode* l2){
ListNode* dummy = new ListNode(-1);
ListNode* node = dummy;
while(l1 && l2){
if(l1->val <= l2->val){
node->next = new ListNode(l1->val);
l1 = l1->next;
} else {
node->next = new ListNode(l2->val);
l2 = l2->next;
}
node = node->next;
}
if(l1) node->next = l1;
if(l2) node->next = l2;
return dummy->next;
}
ListNode* sortList(ListNode* head) {
if(!head || !head->next) return head;
// find mid
ListNode* slow = head;
ListNode* fast = head;
ListNode* prev = slow;
while(fast && fast->next){
prev = slow;
slow = slow->next;
fast = fast->next->next;
}
prev->next = NULL;
ListNode* l1 = sortList(head);
ListNode* l2 = sortList(slow);
return merge(l1, l2);
}
};
반응형