标签:head ListNode 148 next 链表 temp1 return NULL leetcode
leetcode-148. 排序链表
题目:
代码:
#include <iostream>
using namespace std;
typedef struct ListNode{
int val;
ListNode* next;
}ListNode,*ListLink;
void create(ListLink& head){
int n;
cin>>n;
head=new ListNode;
head->next=NULL;
ListNode *r=head;
for(int i=0;i<n;i++){
ListNode *p=new ListNode;
cin>>p->val;
p->next=NULL;
r->next=p;
r=p;
}
}
//快排
/*ListNode* sortList(ListNode* head) {
if(!head){
return head;
}
ListNode* dummy = new ListNode;
dummy->next=head;
ListNode* last=head;
ListNode* cur=head->next;
while(cur){
if(last->val<=cur->val){
last=last->next;
}else{
ListNode* pre=dummy;
while(pre->next->val <= cur->val){
pre=pre->next;
}
last->next=cur->next;
cur->next=pre->next;
pre->next=cur;
}
cur=last->next;
}
return dummy->next;
}*/
ListNode* merge(ListNode* head1, ListNode* head2) {
ListNode* dummyHead = new ListNode;
dummyHead->next=NULL;
ListNode* temp = dummyHead, *temp1 = head1, *temp2 = head2;
while (temp1 != NULL && temp2 != NULL) {
if (temp1->val <= temp2->val) {
temp->next = temp1;
temp1 = temp1->next;
} else {
temp->next = temp2;
temp2 = temp2->next;
}
temp = temp->next;
}
if (temp1 != NULL) {
temp->next = temp1;
} else if (temp2 != NULL) {
temp->next = temp2;
}
return dummyHead->next;
}
//归并排序
ListNode* sort(ListNode* head, ListNode* tail) {
if (head == NULL) {
return head;
}
if (head->next == tail) {
head->next = NULL;
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(sort(head, mid), sort(mid, tail));
}
ListNode* sortList(ListNode* head) {
return sort(head,NULL);
}
int main(){
ListNode* head;
create(head);
head=sortList(head->next);
while(head){
cout<<head->val<<" ";
head=head->next;
}
return 0;
}
标签:head,ListNode,148,next,链表,temp1,return,NULL,leetcode 来源: https://blog.csdn.net/qq_42250642/article/details/121742113
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。