马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 haiouda 于 2015-4-3 13:28 编辑 #include<stdio.h>
#include<malloc.h>
#define LNK sizeof(struct Student) //定义一个宏,长度为结构的长度
int n; //全局变量
struct Student //声明结构
{
long int num;
double score;
struct Student *next;
};
struct Student *inpu(void) //建立链表函数
{
struct Student *p1,*p2,*head;
head=NULL;
p1=p2= (struct Student *)malloc(LNK); //开辟一个新单元
printf("输入学号:");
scanf("%d",&p1->num);
printf("输入成绩:");
scanf("%lf",&p1->score);
while( p1->num)
{
n+=1;
if(n==1) head=p1;
else p2->next=p1;
p2=p1;
p1=(struct Student *)malloc(LNK); //开辟一个新单元
printf("输入学号:");
scanf("%d",&p1->num);
printf("输入成绩:");
scanf("%lf",&p1->score);
}
p2->next=NULL;
return head ;
}
void print(struct Student *head) //输出链表函数
{
struct Student *p;
printf("这个链表共有%d个结点:\n",n);
if(head!=NULL)
{
p=head;
do
{
printf("学号:%d 成绩:%5.2lf\n",p->num,p->score);
p=p->next;
} while(p!=NULL);
}
}
struct Student *insert( struct Student *head) //插入一个结点
{
struct Student *p0,*p1,*p2;
p0=(struct Student *)malloc(LNK);
printf("输入要插入的学号:");
scanf("%d",&p0->num);
printf("输入成绩:");
scanf("%lf",&p0->score);
p0->next=NULL;
p1=p2=head;
if(head== NULL)
{
p0=head;
p0->next=NULL;
}
else
{
while(p0->num > p1->num && p1->next!=NULL )
{
p2=p1;
p1=p1->next;
}
if(p0->num <= p1->num)
{
if(p1 == head ) head=p0;
else
{
p2->next=p0;
}
p0->next=p1;
}
else
{
p1->next=p0;
p0->next=NULL;
}
}
n=n+1;
return head;
}
struct Student *del( struct Student *head) //删除学号
{
struct Student *p1,*p2;
long int num;
printf("输入要删除的学号:");
scanf("%d",&num);
p1=p2=head;
if( head == NULL)
{
printf("这是一个空链表!");
goto END;
}
else
{
while( num != p1->num )
{
p2=p1;
p1=p1->next;
if (p1->next==NULL) break;
}
if( p1==head)
{
head=p1->next;
}
else if(p1->next == NULL)
{
if (num==p1->num) p2->next =NULL;
else
{
printf("输入错误!\n");
goto END;
}
}
else
{
p2->next= p1->next;
}
}
n=n-1;
END:
return head;
}
int main()
{
struct Student *head,*p;
int n;
head=inpu();
do{
printf("n=1时打印链表;n=2时插入;n=3时删除一个学号;n==0退出程序;n=");
scanf("%d",&n);
if (n==0) break; //退出
switch(n)
{
case 1: { p=head; print(p); break; } //打印
case 2: { p=head; head=insert(p); break;} // 添加
case 3: { p=head; head=del(p); break;} // 删除
default:
printf("输入错误!请重新输入\n");
}
}while(1);
return 0;
}
还有木有错误了?
|