#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<string.h>
///////////////////////////
typedef struct Student
{
char name[20];
int mark;
struct Student *next;
} Node, *node;
////////////////////////
///////////////////////////
void Search_All(node head)
{
node p;
p = head->next;
while (p != NULL)
{
printf("姓名:%s\t\t", p->name);
printf("分数:%d\n", p->mark);
p = p->next;
}
}
///////////////////////////////////
Search_Single(char name[20], node head)
{
node p;
p = head->next;
while (p != NULL)
{
if (strcmp(name,p->name) == 0)
{
printf("该学生的分数为:%d", p->mark);
return 0;
}
else
p = p->next;
}
printf ("没有找到该学生!");
return 0;
}
/////////////////////////////////////////
Del_Single(char name[20], node head)
{
node p, q;
p = head;
while (p->next != NULL)
{
if (strcmp(name, p->next->name) == 0)
{
q = p->next;
p->next = p->next->next;
free(q);
printf("该学生记录已删除");
return 0;
}
else
p = p->next;
}
printf("没有找到该学生记录!");
return -1;
}
///////////////////////////////////////////
Add_Single(node head)
{
node p, p1;
p1 = head->next;
while (p1 != NULL)
{
p1 = p1->next;
}
p = (node)malloc(sizeof(Node));
if (p == NULL)
{
printf("内存分配失败!");
exit(1);
}
else
{
printf("输入增加的学生姓名:");
scanf("%s", p->name);
printf("输入增加的学生分数:");
scanf("%d", &p->mark);
p1 = p;
p->next = NULL;
}
printf("增加记录成功!");
printf("查询新纪录:\n");
getch();
Search_All(head);
getch();
}
///////////////////////////////////////////////
void main(void)
{
int num, i;
node head, p ,p1;
char name[20];
char key;
head = (node)malloc(sizeof(Node));
if (head == NULL)
{
printf("内存分配失败!");
exit(1);
}
else
head->next = NULL;
printf("请输入学生人数:\n");
scanf("%d", &num);
printf("请输入学生的信息:\n");
for (i=0; i < num; i++)
{
p = (node)malloc(sizeof(Node));
if ( p == NULL)
{
printf("分配内存失败!");
exit(1);
}
else
{
printf("姓名:");
scanf("%s", p->name);
printf("分数:");
scanf("%d", &p->mark);
printf("\n");
}
if (head->next == NULL)
{
head->next = p;
p1 = p;
}
else
{
p1->next = p;
p1 = p;
}
}
p1->next = NULL; //将最后的指针域置空 很重要
p = head->next;
while ( p!= NULL)
{
printf("姓名:%s\t", p->name);
printf("分数:%d\n", p->mark);
p = p->next;
}
Loop:
system("cls");
printf("1.查询所有学生成绩\n");
printf("2.查询一个学生成绩\n");
printf("3.删除一个学生记录\n");
printf("4.增加一个学生记录\n");
printf("5.退出");
key = getch();
if ( key == '1')
{
system("cls");
Search_All(head);
getch();
goto Loop;
}
else if ( key == '2')
{
system("cls");
printf("输入要查询的学生姓名");
scanf("%s", name);
Search_Single(name, head);
getch();
goto Loop;
}
else if ( key == '3' )
{
system("cls");
printf("请输入要删除记录的学生姓名");
scanf("%s", name);
Del_Single(name, head);
getch();
goto Loop;
}
else if (key == '4')
{
system("cls");
Add_Single(head);
getch();
goto Loop;
}
else if (key == '5')
{
exit(0);
}
}