#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
struct student
{
char num[10];
char name[10];
int age;
char sex[5];
char tel[15];
char addr[50];
struct student *next;//指针域
};
struct student* creat()//尾插法建立带头结点的单链表 ;
{
struct student *head,*r,*stu;
int i=0;
char choice;
head=r=(struct student*)malloc(sizeof(struct student));//创建头结点;r也指向头结点!
head->next=NULL;
do
{
stu=(struct student*)malloc(sizeof(struct student));//创建下一个节点;
printf("\n第%d个人的信息:\n",++i);
printf("\n学号:");
scanf("%s",stu->num);
printf("\n姓名:");
scanf("%s",stu->name);
printf("\n年龄:");
scanf("%d",&stu->age);
printf("\n性别:");
scanf("%s",stu->sex);
printf("\n联系电话:");
scanf("%s",stu->tel);
printf("\n住址:");
scanf("%s",stu->addr);
r->next=stu;//尾插新结点
r=stu;//指向尾节点!
printf("是否继续录入?(Continue?)\n请输入 Y/y(Yes) 或 N/n(No):");//终止条件
choice=getche();
}while(choice=='Y'||choice=='y') ;
r->next=NULL;//录入结束,尾节点指空
return head;
}
void sort(struct student *head)
{
struct student*pre,*p,*tail,*temp;
tail=NULL;
pre=head;
while((head->next->next)!=tail)
{
pre=head;//前一个结点
p=head->next;//后一个结点
while(p->next!=tail)//交换结点法
{
if(strcmp(p->num,p->next->num)>0)
{
pre->next=p->next;
p->next=p->next->next;
pre->next->next=p;
p=pre->next;
}
p=p->next;
pre=pre->next;
}
tail=p;//tail前移
}
}
void print(struct student*h)//打印链表信息;
{
struct student*stu;
printf("\n该班数据为:\n");
printf("学号 姓名 年龄 性别 联系电话 住址\n");
for(stu=h->next;stu!=NULL;stu=stu->next) //有问题!
{
printf("%-8s %-5s %-3d %s %-12s %-15s\n",stu->num,stu->name,stu->age,stu->sex,stu->tel,stu->addr);
}
}
main()
{
struct student *head;
head=creat();
sort(head);
print(head);
}
C语言链表排序
最新推荐文章于 2024-05-15 16:20:58 发布