请编写程序实现链表的建立、插入、删除、遍历的基本运算其中链表中每个数据元素的类型定义为学生信息的结构体包括学号、姓名和成绩。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LEN 20
struct student {
int id;
char name[MAX_NAME_LEN];
int score;
struct student *next;
};
/* 创建一个新节点 */
struct student *create_node(int id, char *name, int score) {
struct student *node = (struct student*)malloc(sizeof(struct student));
if (node == NULL) {
printf("Error: cannot allocate memory.\n");
exit(1);
}
node->id = id;
strncpy(node->name, name, MAX_NAME_LEN);
node->score = score;
node->next = NULL;
return node;
}
/* 在链表末尾插入一个节点 */
void insert_node(struct student **head, struct student *node) {
if (*head == NULL) {
*head = node;
} else {
struct student *p = *head;
while (p->next != NULL) {
p = p->next;
}
p->next = node;
}
}
/* 删除指定学号的节点 */
void delete_node(struct student **head, int id) {
struct student *p = *head;
struct student *prev = NULL;
while (p != NULL) {
if (p->id == id) {
if (prev == NULL) {
*head = p->next;
} else {
prev->next = p->next;
}
free(p);
return;
}
prev = p;
p = p->next;
}
printf("Error: cannot find student with id %d.\n", id);
}
/* 遍历链表并输出每个节点的信息 */
void traverse_list(struct student *head) {
printf("ID\tName\tScore\n");
printf("--------------------------------\n");
struct student *p = head;
while (p != NULL) {
printf("%d\t%s\t%d\n", p->id, p->name, p->score);
p = p->next;
}
}
int main() {
struct student *head = NULL;
/* 构造链表 */
insert_node(&head, create_node(1001, "Alice", 90));
insert_node(&head, create_node(1002, "Bob", 80));
insert_node(&head, create_node(1003, "Charlie", 70));
insert_node(&head, create_node(1004, "David", 60));
/* 遍历链表 */
traverse_list(head);
/* 插入新节点 */
insert_node(&head, create_node(1005, "Emily", 85));
printf("After inserting a new node:\n");
traverse_list(head);
/* 删除节点 */
delete_node(&head, 1002);
printf("After deleting a node:\n");
traverse_list(head);
return 0;
}
原文地址: https://www.cveoy.top/t/topic/01Y 著作权归作者所有。请勿转载和采集!