单链表的尾插(一级指针尾插的缺陷及改进)

1.如果我们一开始就要使用尾插法,就会发现程序出问题了,因为我们原本的逻辑是找到倒数第二个表块,改变它的next使得它指向我们要添加的新表块,在本质上,头指针的作用形式没有任何改变,只是多执行了几次。而现在的情况是这个头指针指向了一个表块没错,但这个表块什么都没有,所以我们需要先“改造”头指针,让它先指向一个完整的表块(改变什么就要操作什么的指针)

#include
#include
typedef struct list biao;
struct list 
{
    int data;
    biao* next;

}list1;
void dataprint(biao* point)
{
    biao* list1 = point;
    while (list1 != NULL)
    {
        printf("%d->", list1->data);
        list1 = list1->next;
    }
    printf("NULL\n");
}
void frontset(biao** point1, int x)
{
  
    biao* point2 = (biao*)malloc(sizeof(biao));
    if (point2 == NULL)
    {
        printf("error about point2");
        return;
    }
    point2->data = x;
    point2->next =*point1;
    *point1 = point2;
}
void backset(biao**point1,int x)
{
    if (*point1 != NULL)
    {
        biao* point2 = *point1;
        while ((point2)->next != NULL)
        {
            point2 = (point2)->next;
        }
        biao* point3 = (biao*)malloc(sizeof(list));
        if (point3 == NULL)
        {
            printf("error of point3");
            return;
        }

        point2->next = point3;

        point3->next = NULL;
        point3->data = x;
    }
    else
    {
        biao*point4 = (biao*)malloc(sizeof(biao));
        point4->data = x;
        point4->next = NULL;
        *point1 = point4;
    }
}
int main()
{
    biao *good = NULL;
    frontset(&good, 1);
    frontset(&good, 2);
    frontset(&good, 3);
    frontset(&good, 4);
    backset(&good, 0);
    dataprint(good);
    return 0;
}

你可能感兴趣的:(数据结构,数据结构)