#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct ListNode {
int val;//编号
char title[50];//书名
float price;//价格
struct ListNode* next;
};
// 在尾部插入节点
struct ListNode* insertAtTail(struct ListNode* head, int val,char mytitle[50],float price) {
struct ListNode* new_node = (struct ListNode*)malloc(sizeof(struct ListNode));
new_node->val = val;
strcpy(new_node->title,mytitle);
new_node->price=price;
new_node->next = NULL;
if (head == NULL) {
return new_node;
}
struct ListNode* p = head;
while (p->next != NULL) {
p = p->next;
}
p->next = new_node;
return head;
}
void listAll(struct ListNode* head){
printf("编号\t书名\t价格\n");
struct ListNode* p=head;
while(p!=NULL){
printf("%d\t%s\t%f", p->val, p->title, p->price);
printf("\n");
p=p->next;
}
}
// 删除指定值的节点
struct ListNode* deleteNode(struct ListNode* head, int val) {
struct ListNode* p = head;
struct ListNode* prev = NULL;
while (p != NULL && p->val != val) {
prev = p;
p = p->next;
}
if (p == NULL) {
return head;
}
if (prev == NULL) {
head = head->next;
} else {
prev->next = p->next;
}
free(p);
return head;
}
// 修改指定值的节点的值
struct ListNode* modifyNode(struct ListNode* head, int old_val,char newTitle[50],float newPrice) {
struct ListNode* p = head;
while (p != NULL && p->val != old_val) {
p = p->next;
}
if (p == NULL) {
return head;
}
strcpy(p->title ,newTitle);
p->price = newPrice;
return head;
}
// 查找指定值的节点的位置
int getIndexByVal(struct ListNode* head, int val) {
struct ListNode* p = head;
int i = 0;
while (p != NULL && p->val != val) {
p = p->next;
i++;
}
if (p == NULL) {
return -1;
}
return i;
}
int main(){
struct ListNode* p=NULL;
for (int i = 0; i < 100; i++)
{
printf("%s", "1.插入图书\n");
printf("%s", "2.删除图书\n");
printf("%s", "3.图书列表\n");
printf("%s", "4.修改图书\n");
printf("%s", "请输入1或2或3或4:\n");
int select;
scanf("%d", &select);
if (select == 1)
{
int myVal;
printf( "请输入编号:\n");
scanf("%d", &myVal);
printf( "请输入书名:\n");
char myTitle[50];
scanf("%s", myTitle);
printf( "请输入价格:\n");
float myPrice;
scanf("%f",&myPrice);
if(p==NULL){
p=insertAtTail(NULL,myVal,myTitle,myPrice);
}else{
p=insertAtTail(p,myVal,myTitle,myPrice);
}
}else if(select==3){
listAll(p);
}else if(select==2){
int deleteVal;
printf("请输入要删除的图书的编号:\n");
scanf("%d",&deleteVal);
p=deleteNode(p,deleteVal);
}else if(select==4){
int modifyVal;
printf("请输入要修改的图书的编号:\n");
scanf("%d",&modifyVal);
if(getIndexByVal(p,modifyVal)==-1){
printf("图书不存在");
continue;
}
printf( "请输入书名:\n");
char modifyTitle[50];
scanf("%s", modifyTitle);
printf( "请输入价格:\n");
float modifyPrice;
scanf("%f",&modifyPrice);
p=modifyNode(p,modifyVal,modifyTitle,modifyPrice);
}
}
return 0;
}
要改成班级管理,ListNode中val不变,其它属性变成学生姓名、成绩等等。
注意:c语言的编译不要用visual studio,因为它连scanf都会报错,会要求您使用scanf_s。建议用记事本或visual studio code编写,然后在命令行窗口输入g***命令来编译。