#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct book
{
char ID[10];
char name[20];
struct book* next;
}book;
book* buynode(char* id, char* na);
void weicha(book** phead, char* id, char* na);
void my_print(book* phead);
void shanchu(book** phead);
int main()
{
book* plist = NULL;
char a[20][20], b[20][20];
int i = 0, j = 0;
printf("输入图书的编号和书名\n");
do
{
scanf("%s %s", a[i], b[i]);
weicha(&plist, a[i], b[i]);
i++;
} while (strcmp(a[i - 1], "0") != 0);
printf("创建的链表\n");
my_print(plist);
printf("请输入要删除的图书的编号\n");
shanchu(&plist);
printf("删除后的链表\n");
my_print(plist);
return 0;
}
book* buynode(char* id, char* na)
{
book* newnode = (book*)malloc(sizeof(book));
if (newnode == NULL)
{
perror("malloc fail");
return NULL;
}
strcpy(newnode->ID, id);
strcpy(newnode->name, na);
newnode->next = NULL;
return newnode;
}
void weicha(book** phead, char* id, char* na)
{
book* newnode = buynode(id, na);
if (*phead == NULL)
{
*phead = newnode;
}
else
{
book* tail = *phead;
while (tail->next != NULL)
{
tail = tail->next;
}
tail->next = newnode;
}
}
void my_print(book* phead)
{
book* cur = phead;
while (cur->next != NULL)
{
printf("%s %s\n", cur->ID, cur->name);
cur = cur->next;
}
printf("\n");
}
void shanchu(book** phead)
{
char c[10];
scanf("%s", c);
book* daishan = *phead;
while (strcmp(daishan->ID, c) != 0)
{
daishan = daishan->next;
}
if (daishan == *phead)
{
book* del = *phead;
*phead = del->next;
}
else
{
book* prev = *phead;
while (prev->next != daishan)
{
prev = prev->next;
}
prev->next = daishan->next;
free(daishan);
}
}
用链表和结构体实现对图书信息的储存,删除及显示功能
最新推荐文章于 2024-05-08 21:30:04 发布