#include<iostream>
#include<stdio.h>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* sortList(ListNode* head) {
return mergesort2(head);
}
ListNode* mergesort2(ListNode* head)
{
if(head==NULL||head->next==NULL) return head;
ListNode *fast=head,*slow=head;
while(fast->next!=NULL&&fast->next->next!=NULL)
{
fast=fast->next->next;
slow=slow->next; //找到中间点,slow
}
fast=slow; //fast 指向队尾
slow=slow->next;
fast->next=NULL;
ListNode* l1=mergesort2(head);
ListNode* l2=mergesort2(slow);
mergeTwoLists(l1,l2);
}
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2)
{
ListNode *helper=new ListNode(0);
ListNode *head=helper;
while(l1 && l2)
{
if(l1->val<l2->val) helper->next=l1,l1=l1->next;
else helper->next=l2,l2=l2->next;
helper=helper->next;
}
if(l1) helper->next=l1;
if(l2) helper->next=l2;
return head->next;
}
};
int main() {
Solution solution;
//int A[] = {2,4,7,9};
//int B[] = {5,6,4};
int i;
ListNode *head = NULL;
ListNode *head1 = (ListNode*)malloc(sizeof(ListNode));
ListNode *head2 = (ListNode*)malloc(sizeof(ListNode));
head1->next = NULL;
head2->next = NULL;
ListNode *node;
ListNode *pre = head1;
for(int i = 5;i >0;i--){
node = new ListNode(i);
// node->exp = A[i];
node->next = NULL;
pre->next = node;
pre = node;
}
/* pre = head2;
for(int i = 2;i < 5;i++){
node = new ListNode(i,i+1);
// node->val = B[i];
node->next = NULL;
pre->next = node;
pre = node;
}*/
head = solution.sortList(head1->next);
while(head != NULL){
// printf("%d %d ",head->coef,head->exp);
cout<<head->val<<' ';
head = head->next;
}
//i=(head1->val);
//cout<<i;
return 0;
}