add: 220224 [cpp]

This commit is contained in:
Lam Haoyin 2022-02-24 17:05:43 +08:00
parent 5d08132f87
commit e0010f865d
No known key found for this signature in database
GPG Key ID: 8C089CB1A2B7544F
2 changed files with 38 additions and 1 deletions

37
cpp/2202/220224.cpp Normal file
View File

@ -0,0 +1,37 @@
#include <vector>
#include <algorithm>
/**
* Definition for singly-linked list.
*/
struct ListNode {
int val;
ListNode* next;
ListNode(int x = 0, ListNode* next = nullptr) : val(x), next(next) {}
};
/**
* 148. Sort List
* Given the head of a linked list, return the list after sorting it in ascending order.
*/
class Solution {
public:
static ListNode* sortList(ListNode* head) {
if (!head)
return nullptr;
std::vector<ListNode*> arr;
for (ListNode* ptr = head; ptr; ptr = ptr->next)
arr.push_back(ptr);
std::sort(arr.begin(), arr.end(), [](ListNode* x, ListNode* y){ return x->val < y->val; });
int n = arr.size();
for (int i = 0; i < n - 1; ++i)
arr[i]->next = arr[1 + i];
arr.back()->next = nullptr;
return arr[0];
}
};
int main() {
return 0;
}

View File

@ -3,4 +3,4 @@ PROJECT(2202)
SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2202 220224-CN.cpp)
ADD_EXECUTABLE(2202 220224.cpp)