题目不难,记录一下老老实实用链表实现的方法
写一个建立单链表的函数,设链表的表元素包含学号、姓名、一门课的成绩,要求按学号从小到大输入链表结点数据;写一个插入一条学生记录的函数;最后写一个主函数,先调用建立函数,然后输入要插入的学生信息,再调用插入函数,最后输出显示插入后的链表全部信息。
输入
前几行是一组学生信息,每行一个学生包括学号、姓名、成绩,当输入学号为0结束;
最后一行是一条学生记录,是待插入的学生学号、姓名、成绩插入
输出
插入后链表信息,每行一条记录; 如果该学号已存在,则输出“Record exists!”
样例输入
1 Wangli 77 3 Lishi 88 4 Zhangsan 87 5 Cuidi 90 7 Zhaowu 67 8 Wuwei 86 0 2 Xuchen 75
样例输出
1 Wangli 77 2 Xuchen 75 3 Lishi 88 4 Zhangsan 87 5 Cuidi 90 7 Zhaowu 67 8 Wuwei 86
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义学生结构体
typedef struct Student {
int id;
char name[50];
int score;
struct Student *next;
} Student;
// 创建链表函数
Student* createLinkedList() {
Student *head = NULL;
Student *current = NULL;
int id, score;
char name[50];
// 输入学生信息,直到学号为0结束
while (1) {
scanf("%d", &id);
if (id == 0) break;
scanf("%s %d", name, &score);
Student *newNode = (Student *)malloc(sizeof(Student));
newNode->id = id;
strcpy(newNode->name, name);
newNode->score = score;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
current = newNode;
} else {
current->next = newNode;
current = newNode;
}
}
return head;
}
// 插入学生记录函数
void insertRecord(Student *head, int id, char name[], int score) {
Student *current = head;
Student *prev = NULL;
// 遍历链表找到插入位置
while (current != NULL) {
if (current->id == id) {
printf("Record exists!\n");
return;
} else if (current->id > id) {
break;
}
prev = current;
current = current->next;
}
// 创建新节点并插入链表
Student *newNode = (Student *)malloc(sizeof(Student));
newNode->id = id;
strcpy(newNode->name, name);
newNode->score = score;
newNode->next = current;
if (prev == NULL) {
head = newNode;
} else {
prev->next = newNode;
}
}
// 打印链表函数
void printLinkedList(Student *head) {
Student *current = head;
while (current != NULL) {
printf("%d %s %d\n", current->id, current->name, current->score);
current = current->next;
}
}
int main() {
Student *head = createLinkedList();
int id, score;
char name[50];
scanf("%d %s %d", &id, name, &score);
insertRecord(head, id, name, score);
printLinkedList(head);
// 释放链表内存
Student *temp;
while (head != NULL) {
temp = head;
head = head->next;
free(temp);
}
return 0;
}