单链表 尾插法
void addnub(struct num **numble,int i){
struct num *pre;
struct num *now;
struct num *crt;
now=(struct num *)malloc(sizeof(struct num));
if(now->next==NULL) printf("HHHH\n");
now->n=i;
if(*numble==NULL)
{
*numble=now;
now->next=NULL;
}
else
{
pre=*numble;
while(pre->next!=NULL)
{
pre=pre->next;
}
pre->next=now;
now->next=NULL;
}
}
运行有错误 不知道哪里出问题了 辛苦指点一下 之前写的一个图书程序,可以参考下
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;
页:
[1]