键盘输入8个学生的成绩数据,学生信息包括学号,姓名和成绩,创立一个动态链表,并对其中的某学号进行修改
话不多说直接上代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct student {
int xh; // 学号
char name[100]; // 姓名
int chengji; // 成绩
} STU;
typedef struct node {
STU stu;
struct node* next;
} S;
S* initialize()
{
S* h;
h = (S*)malloc(sizeof(S));
h->next = NULL;
return h;
}
// 向链表末尾添加节点
void append(S* head, STU stu1)
{
S* p;
p = (S*)malloc(sizeof(S));
p->stu = stu1;
p->next = head->next;
head->next = p;
}
// 输入学生信息
int input(S* head, int numstudents)
{
STU temp;
int n = 0;
for (int i = 0; i < numstudents; i++)
{
printf("请输入第%d个学生的信息(学号 姓名 成绩):", i + 1);
scanf("%d %s %d", &temp.xh, temp.name, &temp.chengji);
append(head, temp);
n++;
}
return n;
}
// 输出链表中的学生信息
void output(S* head)
{
S* p;
p = head;
for (p = head->next; p != NULL; p = p->next)
{
STU temp = p->stu;
printf("%d %s %d\n", temp.xh, temp.name, temp.chengji);
}
}
// 根据学号查找学生并修改信息
void find(S* head, int xh)
{
S* p;
for (p = head->next; p != NULL; p = p->next)
{
if (p->stu.xh == xh)
{
printf("请输入学号为%d的学生的新信息(姓名 成绩):", xh);
scanf("%s %d", p->stu.name, &p->stu.chengji);
printf("修改成功\n");
return;
}
}
printf("未找到学号为%d的学生。\n", xh);
}
// 使用冒泡排序对学生信息按照成绩从小到大进行排序
void sortstudents(S* head)
{
int swapped;
S* ptr1;
S* ptr = NULL;
if (head->next == NULL)
{
return;
}
do {
swapped = 0;
ptr1 = head->next;
while (ptr1->next != ptr) {
if (ptr1->stu.chengji > ptr1->next->stu.chengji) {
STU temp = ptr1->stu;
ptr1->stu = ptr1->next->stu;
ptr1->next->stu = temp;
swapped = 1;
}
ptr1 = ptr1->next;
}
ptr = ptr1;
} while (swapped);
}
int main()
{
S* head;
head = initialize();
printf("请输入学生信息:");
int numstudents = 8;
input(head, numstudents);
printf("原始学生信息:\n");
sortstudents(head);
output(head);
int target;
printf("请输入要修改信息的学生学号:");
scanf("%d", &target);
find(head, target);
printf("更新后的学生信息:\n");
sortstudents(head);
output(head);
S* p = head->next;
while (p != NULL)
{
S* temp = p;
p = p->next;
free(temp);
}
free(head);
return 0;
}
还有一种大同小异的方法
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct Stu {
int ID;
char name[20];
int score;
struct Stu *next;
};
struct Stu * create()
{
struct Stu *head,*p,*rear;
int n=0;
int id,tempscore;
char Name[20];
while(1)
{
scanf("%d%s%d",&id,Name,&tempscore);
if(id==-1) break;
n++;
p=(struct Stu *)malloc(sizeof(struct Stu));
p->ID=id;
strcpy(p->name,Name);
p->score=tempscore;
p->next=NULL;
if(n==1)
{
head=p;
rear=p;
p=p->next;
}
else
{
rear->next=p;
p=p->next;
rear=rear->next;
}
}
return head;
}
void display(struct Stu * head)
{
struct Stu *p;
p=head;
while(p!=NULL)
{
printf("%d %s %d\n",p->ID,p->name,p->score);
p=p->next;
}
}
int main()
{
struct Stu *head;
head=create();
display(head);
return 0;
}
有不懂的后台私信哦~~