#include<stdio.h>
#include<stdlib.h>
//链表
typedef struct book
{
char name[10];
int code;
float price;
} book;
typedef book Book;
typedef struct List
{
Book data;
struct List *next;
} LNode;
//初始化
void InitList(struct List *L)
{
L=(LNode*)malloc(sizeof(LNode));
if (!L)
{
printf("初始化失败!\n");
exit(1);
}
L->next=NULL;
}
//创建(带头结点,尾插法)
void creatList(struct List *L)
{
LNode *head,*s,*p;
Book b;
head=(LNode*)malloc(sizeof(LNode));
head=L;
head->next=NULL;
p=head;
printf("开始创建链表,当输入的price小于等于0创建结束,最后的元素不接入链表。\n");
printf("请输入book的name、code和price:\n");
scanf("%s%d%f",&b.name,&b.code,&b.price);
while (b.price>0)
{
s=(LNode*)malloc(sizeof(LNode));
s->data=b;
p->next=s;
s->next=NULL;
p=s;
printf("请输入book的name、code和price:\n");
scanf("%s%d%f",&b.name,&b.code,&b.price);
}
printf("链表创建成功!\n");
}
//长度
int LengthList(struct List *L)
{
int i;
struct List *p;
p=L;
i=0;
while (p->next!=NULL)
{
i++;
p=p->next;
}
return i;
}
//查询(按位查询)
Book GetList(struct List *L ,int i)
{
int k;
Book b;
LNode *p;
p=L;
if (i<1||i>LengthList(L))
{
printf("查询越界!\n");
exit(1);
}
k=0;
while (p->next!=NULL)
{
p=p->next;
k++;
if (k==i)
{
printf("成功查询到第%d个元素!\n",i);
b=p->data;
break;
}
}
return b;
}
//插入
void InsList(struct List *L,int i,Book b)
{
int k;
LNode *p,*s;
p=L;
if (i<1||i>LengthList(L)+1)
{
printf("越界插入!\n");
exit(1);
}
k=0;
while (1)
{
if (k==i-1)
{
s=(LNode*)malloc(sizeof(LNode));
s->data=b;
s->next=p->next;
p->next=s;
printf("在第%d个位置上成功插入元素!\n",i);
break;
}
p=p->next;
k++;
}
}
//删除
Book DelList(struct List *L,int i)
{
int k;
Book b;
LNode *p,*q;
p=L;
if (i<1||i>LengthList(L))
{
printf("删除越界!\n");
exit(1);
}
k=0;
while (1)
{
p=p->next;
k++;
if (k==i-1)
{
b=p->next->data;
q=p->next;
p->next=q->next;
free(q);
printf("成功删除了第%d个元素!\n",i);
break;
}
}
return b;
}
//清空
void ClearList(struct List *L)
{
LNode *p,*r;
p=L;
while (p)
{
p=p->next;
r=p;
free(p);
p=r;
}
L->next=NULL;
printf("清空成功!\n");
}
//销毁
void DestroyList(struct List *L)
{
LNode *p,*r;
p=L;
while (p)
{
r=p->next;
free(p);
p=r;
}
// L->next=NULL;
printf("销毁成功!\n");
}
void main()
{
int i,j;
LNode L,*Q;
Q=&L;
Book b,b1,b2;
InitList(&L);
creatList(&L);
j=LengthList(&L);
printf("链表长度:%d\n",j);
//插入
printf("请输入要插入书本的name、code和price:\n");
scanf("%s%d%f",&b1.name,&b1.code,&b1.price);
InsList(&L,1,b1);
//删除
b2=DelList(&L,2);
printf("删除的元素的name:%s, code:%d ,price: %f\n",b2.name,b2.code,b2.price);
//遍历链表
for(i=0;i<LengthList(&L);i++)
{
b=GetList(&L,i+1);
printf("name: %s, code: %d, price: %f\n",b.name,b.code,b.price);
}
// //清空
// ClearList(&L);
// printf("链表长度:%d\n",LengthList(&L));
//销毁
DestroyList(&L);
printf("链表长度:%d\n",LengthList(Q));
//遍历链表
for(i=0;i<LengthList(&L);i++)
{
b=GetList(&L,i+1);
printf("name: %s, code: %d, price: %f\n",b.name,b.code,b.price);
}
}

不知道你这个问题是否已经解决, 如果还没有解决的话:
如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 以帮助更多的人 ^-^