鱼C论坛

 找回密码
 立即注册
查看: 2458|回复: 1

单链表 尾插法

[复制链接]
发表于 2020-2-18 18:54:54 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
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;
        }

}


运行有错误 不知道哪里出问题了 辛苦指点一下
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2020-2-25 17:12:39 | 显示全部楼层
之前写的一个图书程序,可以参考下
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;
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-7-7 16:18

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表