链表的插入排序。
这是带头结点的链表排序,不带头结点的链表排序只是将相应的head减少了一个next域,所以凡是有head的地方都减少一个->next域。
//不带头结点的链表插入排序
link sort(link head)
{
link frist;//未排序的第一个结点;
link post;//有序链表的第一个结点(即head->next);
link prew;//应插入位置的前一个结点;
link sert;//待插入的结点;
link t;
frist=head->next;
head->next=NULL;
while(frist!=NULL)
{
sert=frist;
post=head;
while(post!=NULL&&post->date<sert->date)//找到要插入位置的前一个结点;
{
prew=post;//使用prew标记要插入位置的前一个结点;
post=post->next;//用post进行查找要插入的位置 ;
}
frist=frist->next;//这里位置不能换;
if(post==head)//判断是不是头结点;
{
head=sert;
}
else
{
prew->next=sert;//否则插入要插入位置的前一个结点后;
}
sert->next=post;//插入后连接原来有序链表;
}
return head;
}
带头结点的链表插入排序
#include <stdio.h>
#include <stdlib.h>
typedef struct num{
int date;
struct num *next;
}list,*link;
void print(link head);
link create(link head)
{
link temp,pnew;
head=(link)malloc(sizeof(list));
temp=head;
int x;
scanf("%d",&x);
while(x!=0)
{
pnew=(link)malloc(sizeof(list));
pnew->date=x;
pnew->next=NULL;
temp->next=pnew;
temp=pnew;
scanf("%d",&x);
}
return head;
}
link sort(link head)
{
link frist; // 待排序的第一个元素
link post;
link sert; // 待排序的第一个元素
link prev; // 要插入的前一个元素
frist=head->next->next; // frist为链表的第二个结点(默认第一个结点已排序)
head->next->next=NULL; // 置第二个结点的next为NULL;
while(frist!=NULL) //当frist为NULL,表示已无未排序的结点
{
sert=frist;
post=head->next;
while(post!=NULL&&post->date<sert->date) // 找到要插入的地方
{
prev=post; // prev为要插入的前一个结点
post=post->next; // post为插入结点的后一个结点
}
frist=frist->next; // 找到未排序的第一个结点
if(post==head->next) //if()else()就是将找到的要插入结点插入到相应的位置
{
head->next=sert;
}
else
{
prev->next=sert;
}
sert->next=post; //插入的结点指向下一个结点post
print(head);
printf("\n");
}
return head;
}
void print(link head)
{
link p;
p=head->next;
while(p!=NULL)
{
printf("%d ",p->date);
p=p->next;
}
}
int main()
{
link head;
head=create(head);
head=sort(head);
}