#include<stdio.h>
#include<stdlib.h>
typedef int T;
typedef struct node {
T element;
struct node* Link;
}Node;
typedef struct list {
Node* First;
}List;
Node* NewNode(T x) {
Node* n = (Node*)malloc(sizeof(Node));
n->element = x;
n->Link = NULL;
return n;
}
Node* Merge(Node * p, Node * q) {
Node* rear, head;
rear = &head;
while (p!=NULL && q!=NULL)
{
if (p->element <= q->element)
{
rear->Link = p;
rear = p;
p = p->Link;
}
else {
rear->Link = q;
rear = q;
q = q->Link;
}
}
if (p==NULL)
{
rear->Link= q;
}
else {
rear->Link = p;
}
return head.Link;
}
Node* Divide(Node* p) {
Node* pos, * mid, * q;
if ((mid=p) == NULL)
{
return NULL;
}
pos = mid->Link;
while (pos!=NULL)
{
pos = pos->Link;
if (pos!=NULL)
{
mid = mid->Link;
pos = pos->Link;
}
}
q = mid->Link;
mid->Link = NULL;
return q;
}
void RMSort(Node** sublst) {
if (*sublst!=NULL && (*sublst)->Link!=NULL)
{
Node* second = Divide(*sublst);
RMSort(sublst);
RMSort(&second);
*sublst = Merge(*sublst, second);
}
}
void RMergeSort(List * lst) {
RMSort(&lst->First);
}
void CreateList(List* lst, T headElem) {
lst->First = NewNode(headElem);
}
void AddNode(List* lst, T elem) {
Node* temp = NewNode(elem);
Node* rear;
rear = lst->First;
for (; rear->Link; rear = rear->Link);
rear->Link = temp;
}
void PrintList(List* lst) {
Node* rear;
rear = lst->First;
for (; rear; rear = rear->Link) {
printf("%-6d ", rear->element);
}
printf("\n");
}
void main() {
List* lst = (List*)malloc(sizeof(List));
CreateList(lst, 26);
AddNode(lst, 33);
AddNode(lst, 35);
AddNode(lst, 29);
AddNode(lst, 19);
AddNode(lst, 12);
AddNode(lst, 22);
PrintList(lst);
RMergeSort(lst);
PrintList(lst);
}
result:
26 33 35 29 19 12 22
12 19 22 26 29 33 35