链表插入排序
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
typedef struct _Node
{
int val;
struct _Node* next;
}Node;
typedef struct _Node List;
List* Head = NULL,*Tail=NULL;
int AddNode(int val)
{
Node* node = (Node*)malloc(sizeof(Node));
if(node == NULL)
return 1;
if(Head == NULL)
Tail = node;
node->val = val;
node->next = Head;
Head = node;
return 0;
}
void FreeList(List* head)
{
Node* tmp = NULL;
while(head != NULL)
{
tmp = head;
head = head->next;
free(tmp);
}
}
void PrintList(List* head)
{
Node* tmp=head;
while(tmp != NULL)
{
printf("%3d ",tmp->val);
tmp=tmp->next;
}
printf("\n");
}
void InsertSort(List** head,List* end)
{
Node *newlist=end;
Node *walk,*save;
walk = *head;
for(;walk != end;walk=save)
{
Node** pnewlink;
for(pnewlink=&newlist;
*pnewlink != end && walk->val >= (*pnewlink)->val;
pnewlink = &((*pnewlink)->next));
save = walk->next;
walk->next = *pnewlink;
*pnewlink = walk;
}
*head = newlist;
}
int main(int argc,char* argv[])
{
int count = 0;
srand(time(NULL));
while(count < 25)
{
AddNode(rand()%1000);
count ++;
}
PrintList(Head);
InsertSort(&Head,NULL);
PrintList(Head);
FreeList(Head);
return 0;
}