#include<stdio.h>
#include<stdlib.h>
typedef struct student
{
int num;
int score;
struct student *next;
}NODE;//学生信息存储结构
NODE *create()
{
NODE *head,*pNew,*pLast;
int num,score;
head=(NODE*)malloc(sizeof(NODE));
if(head==NULL)
{
printf("创建失败!\n");
return (NULL) ;
}
head->next=NULL;
pLast=head;
while (1)
{
printf("请输入学生学号,当学号为0时退出");
scanf ("%d",&num);
if (num==0) break;
printf ("请输入学生成绩");
scanf ("%d", &score) ;
pNew=(NODE*) malloc(sizeof(NODE));
if(pNew==NULL)
{
printf("创建失败!\n");
return (NULL) ;
}
pNew->num=num;
pNew->score=score;
pNew-> next=NULL;
pLast->next=pNew;
pLast=pNew;
}
return head;
}// 创建链表
void print(NODE *head)
{
NODE*p;
printf("链表结点信息如下: \n");
printf("学号\t分数\n");
for(p=head->next;p!=NULL;p=p->next)
printf("%d\t%d\n",p->num,p->score);
} //输出链表
void deleteList(NODE*head,int number)
{
NODE*p=head,*q=head->next;
while(q!=NULL && q->num!=number)
{ p=q;q=q->next;}
if(q==NULL)
{
printf("所要删除的结点不存在!!\n");
return;
}
p->next=q->next;
free (q) ;
} //删除链表元素
void insertNode(NODE *head,int i,NODE *pNew)
{
int j=0;NODE *p;
p=head;
while(p!=NULL && j<i)
{ p=p->next; j++;}
if (p==NULL)
printf ("插入的位置i太大\n") ;
else
{
pNew->next=p->next;
p-> next=pNew;
}
} //插入链表元素
int main()
{
NODE *list,*pNew;
int number,score,location,choice;
list=create();
while(1){
printf("\t\t*****************************\n");
printf("\t\t**请输入1,2,3,4选择相应操作**\n");
printf("\t\t********1.显示链表结点*******\n");
printf("\t\t********2.删除链表结点*******\n");
printf("\t\t********3.插入链表结点*******\n");
printf("\t\t********4.退出程序 *******\n");
printf("\t\t*****************************\n");
scanf ("%d",&choice);
if(choice==4)
break;
else if (choice==1)
{
print(list);
}
else if (choice==2)
{
printf("请输入要删除的学号:\n");
scanf ("%d", &number) ;
deleteList(list,number);
}
else if (choice==3)
{
printf("请输入要插入的位置:\n");
scanf("%d", &location);
pNew=(NODE*)malloc(sizeof(NODE));
if(pNew==NULL)
{
printf("创建新结点失败\n");
continue ;
}
printf("请输入要插入学生结点的学号和成绩:\n");
scanf("&d&d", &number, &score) ;
pNew->num=number;
pNew->score=score;
insertNode(list, location,pNew);
}
else
{
printf("输入有误,请重新输入\n");
continue;
}
}
return 0;
}//主函数
运行效果