#include<stdio.h>
#include<stdlib.h>
#define LEN sizeof(struct Student)
struct Student{
long no;
float score;
struct Student *next;
};
int n;
//动态建立链表
struct Student *creat(void){
struct Student *head;
struct Student *p1,*p2;
n=0;
p1=p2=(struct Student *)malloc(LEN);
printf("请输入链表元素(两组数据之间以空格分开,以0结束):");
scanf("%ld %f",&p1->no,&p1->score);
head = NULL;
while(p1->no!=0){
n=n+1;
if(n==1){
head = p1;
}
else p2->next=p1;
p2=p1;
p1=(struct Student *)malloc(LEN);
printf("请输入链表元素(两组数据之间以空格分开,以0结束):");
scanf("%ld %f",&p1->no,&p1->score);
}
p2->next=NULL;
return (head);
}
//打印链表
void print(struct Student *head){
struct Student *p;
printf("\nThese %d recodes are:\n",n);
p=head;
if(head!=NULL){
do{
printf("%ld %5.1f\n",p->no,p->score);
p=p->next;
}while(p!=NULL);
}
}
//删除链表中的某项
struct Student *delete(struct Student *head){
struct Student *p, *temp;int i=0,count;
printf("请输入删除位置:");
scanf("%d",&count);
if(count<=n){
if(head!=NULL){
do{
i++;
if(count==1&&i==count){
head = head->next;
p = head;
}else{
if(i==count){
temp = p->next;
p->next= temp->next;
n--;
free(temp);
} else{
if(i==1) p = head;
else p=p->next;
}
}
}while(p!=NULL);
}
}else{
printf("你输入的位置不存在!");
}
return (head);
}
//在链表中添加
struct Student *add(struct Student *head){
struct Student *p, *temp; int i=0,count;
printf("请输入插入位置:");
scanf("%d",&count);
if(count<=n){
temp = (struct Student *)malloc(LEN);
if(head!=NULL){
do{
if(count==0&&i==count){
printf("请输入链表元素:");
scanf("%ld %f",&temp->no,&temp->score);
temp->next=head;
head=temp;
n++;
}else{
if(i==count){
printf("请输入链表元素:");
scanf("%ld %f",&temp->no,&temp->score);
temp->next=p->next;
p ->next=temp;
n++;
p=temp;
} else{
if(i==0) p = head;
else p=p->next;
}
}
i++;
}while(p!=NULL);
}
}else{
printf("你输入的位置不存在!");
}
return (head);
}
//打印指定位置链表元素
void check(struct Student *head){
struct Student *p, *temp; int i=0,count;
printf("请输入制定位置:");
scanf("%d",&count);
if(count<=n){
printf("\nThe recode is:\n");
p = head;
if(head!=NULL){
do{
i++;
if(i==count){
printf("%ld %5.1f\n",p->no,p->score);
break;
}
p=p->next;
}while(p!=NULL);
}
}
else{
printf("你输入的位置不存在!");
}
}
menu(){
printf("======菜单======\n");
printf("1.打印链表元素\n");
printf("2.打印指定位置的元素\n");
printf("3.插入元素(在输入的位置之后)\n");
printf("4.删除元素\n");
printf("5.重置链表\n");
printf("0.退出\n");
printf("================\n");
}
//主函数
int main()
{
struct Student *head;int j;
head=creat();
while(1){
menu();
scanf("%d",&j);
switch(j){
case 1: print(head);
break;
case 2: check(head);
break;
case 3: head=add(head);
break;
case 4: head=delete(head);
break;
case 5: head = creat();
break;
case 0: exit(0);
defalut :
printf("你的选择无效,请再次选择!");
break;
}
}
return 0;
}