之前写的一个图书程序,可以参考下struct Book *book,*temp;
book = (struct Book*)malloc(sizeof(struct Book));
if(book == NULL)
{
printf("内存分配失败\n");
exit(1);
}
getInput(book);
if(*library != NULL)
{
temp = library;
while(temp->next != NULL)
{
temp = temp->next;
}
temp->next = book;
book->next = NULL;
}
else
{
*library = book;
book->next = NULL;
}
上方法每次都需要遍历一遍链表,效率低下,可以改成以下void addBook_Wei(struct Book **library)
{
struct Book *book;
static struct Book *tail;//静态结构指针变量
book = (struct Book *)malloc(sizeof(struct Book));
if(book == NULL)
{
printf("内存分配失败\n");
exit(1);
}
getInput(book);//输入结构体内的元素
if(*library != NULL)//若链表有元素
{
tail->next = book;
book->next = NULL;
}
else//若链表没有元素
{
*library=book;
book->next = NULL;
}
tail = book;
|