说说自己做的过程中的几个错误吧。
1忽略了空链表的情况。
2两个链表进行并归排序的时候,应该拿函数返回的头结点,而不是划分的头结点,因为在递归的过程中,最初的头结点可能因为排序而后移了。
3快慢指针的问题条件的判断。
#include <iostream>
#include <map>
#include <vector>
#include<cstdlib>
#include <ctime>
#include <fstream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode *sortList(ListNode *head) {
ListNode* pf = head,*ps = head;
if(!head) return 0;
while(pf->next&&pf->next->next) {
pf=pf->next->next;
ps=ps->next;
}
//pf->val ps->val head->val ans->val
pf= ps->next; ps->next=0;
ListNode* head1=head,*head2=pf;
if(head&&head->next) head1=sortList(head);
if(pf&&pf->next) head2=sortList(pf);
ListNode* ans = new ListNode(-1);
ListNode* ans1 = ans;
while(head1&&head2) {
if(head1->val<=head2->val) {ans->next=head1;head1=head1->next;}
else if(head1->val>head2->val) {ans->next=head2;head2=head2->next;}
ans = ans->next;
}
ans->next=head1?head1:head2;
return ans1->next;
}
int main() {
int t;
srand(time(0));
cin>>t;
ListNode* tmp,*head;
tmp = new ListNode(-1);
head = tmp;
for (int i=0;i<t;i++) {
int data = rand()%100;
// int data;
// cin>>data;
cout<<data<<" ";
ListNode* k = new ListNode(data);
tmp->next = k;
tmp=tmp->next;
}
cout<<endl;
head = sortList(head->next);
while(head) {
cout<<head->val<<" ";
head = head->next;
}
}