20230426 顺利通过
题目
约束
题解
方法一
class Solution {
public:
ListNode* sortList(ListNode* head) {
return sortList(head, nullptr);
}
ListNode* sortList(ListNode* head, ListNode* tail) {
if (head == nullptr) {
return head;
}
if (head->next == tail) {
head->next = nullptr;
return head;
}
ListNode* slow = head, *fast = head;
while (fast != tail) {
slow = slow->next;
fast = fast->next;
if (fast != tail) {
fast = fast->next;
}
}
ListNode* mid = slow;
return merge(sortList(head, mid), sortList(mid, tail));
}
ListNode* merge(ListNode* head1, ListNode* head2) {
ListNode* dummyHead = new ListNode(0);
ListNode* temp = dummyHead, *temp1 = head1, *temp2 = head2;
while (temp1 != nullptr && temp2 != nullptr) {
if (temp1->val <= temp2->val) {
temp->next = temp1;
temp1 = temp1->next;
} else {
temp->next = temp2;
temp2 = temp2->next;
}
temp = temp->next;
}
if (temp1 != nullptr) {
temp->next = temp1;
} else if (temp2 != nullptr) {
temp->next = temp2;
}
return dummyHead->next;
}
};
方法二(常考)
/**
* 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* sortList(ListNode* head) {
if(head == nullptr){
return head;
}
int len = 0;
ListNode* node = head;
while(node != nullptr){
len ++;
node = node->next;
}
ListNode* dummy = new ListNode(0, head);
for(int sublen = 1; sublen < len; sublen <<= 1){
ListNode* pre = dummy,* curr = dummy->next;
while(curr != nullptr){
ListNode* head1 = curr;
for(int i = 1; i < sublen && curr->next != nullptr; i++){
curr = curr->next;
}
ListNode* head2 = curr->next;
curr->next = nullptr;
curr = head2;
for(int i = 1; i < sublen && curr != nullptr && curr->next != nullptr; i++){
curr = curr->next;
}
ListNode* next = nullptr;
if(curr != nullptr){
next = curr->next;
curr->next = nullptr;
}
ListNode* merged = mergerList(head1, head2);
pre->next = merged;
while(pre->next != nullptr){
pre = pre->next;
}
curr = next;
}
}
return dummy->next;
}
ListNode* mergerList(ListNode* head1, ListNode* head2){
if(head1 == nullptr){
return head2;
}else if(head2 == nullptr){
return head1;
}else if(head1->val < head2->val){
head1->next = mergerList(head1->next, head2);
return head1;
}else{
head2->next = mergerList(head1, head2->next);
return head2;
}
}
};
分类:
LeetCode
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)