3.定义一个结构体:
完成由Node类型结点构成的一个单向链表的正向排序(由小到大)#include
#include
struct Node
{
struct Node *next;
int value;
};
struct Node* InsertSort(void)
{
struct Node *Head=NULL,*New,*Cur,*Pre;
int i;
for(i=0;i<5;i++)
{
if((New=(struct Node*)malloc(sizeof(struct Node)))==NULL)
{
printf("申请空间失败\n");
return NULL;
}
printf("请输入节点的value\n");
scanf("%d",&New->value);
New->next=NULL;
if(Head==NULL)
{
Head=New;
continue;
}
if(New->value<=Head->value)
{//head之前插入节点
New->next=Head;
Head=New;
continue;
}
Cur=Head;
while(New->value>Cur->value && Cur->next!=NULL)
{
Pre=Cur;
Cur=Cur->next;
}
if(Cur->value>=New->value)
{
Pre->next=New;
New->next=Cur;
}
else
//if(Cur!=New)
Cur->next=New;
}//for
return Head;
}
void print(struct Node* Head)
{
struct Node* Cur;
Cur=Head;
while(Cur!=NULL)
{
printf("Cur->value=%d\n",Cur->value);
Cur=Cur->next;
}
}
void main(void)
{
struct Node* head;
head=InsertSort();
print(head);
}
程序已经调试通过,大家可以试试。这个题目也应该会,这个在课堂上要求过。插入一个有序单链表。这个题目只是笔试题,如果写出来的程序不能完全执行,这个可以原谅的。如果大体的程序框架都写不出来,这个可要自己仔细想想了。其实这个题目我在204班做了试验,效果也不好。但通过1堂课的练习,不断的调试,每个人还是都写出了可执行的程序。所以学习程序最重要的是多动手啊。