为什么在尝试将新节点插入列表时出错

Why do I get errors while trying to insert a new node to a list

本文关键字:插入 插入列 列表 出错 节点 新节点 为什么      更新时间:2023-10-16

我有一个声明堆栈和列表的头。我正试图将的一个节点添加到列表中,但我没能做到。有人能帮我弄清楚为什么这个功能不起作用吗?

****这两个代码都是头文件中的删除***

/* a link that contains a positive integer value*/
struct link
{
    int value;
    struct link *next;
};

typedef struct link link;
typedef struct
{
    link *head;
} linkedList;
/* a positive-integer value stack, with no size limit */
typedef struct stack
{
    int count;
    int maxSize;
    bool empty;
    linkedList* list;
} stack;

现在我要做的是:

void add(linkedList *list, int newValue)
{
    linkedList* temp = list;

    while (temp->head)
    {
        temp->head = temp->head->next;
    }

    temp->head->next->value = newValue;   //<---- this line is making the error
}
// add new link in the beginning of list with newValue in it

add中,您当前正在修改temp->head以遍历列表。temp是一个局部变量,但它指向真实的链表,因此当您分配给temp->head时,它会修改列表本身的结构。

我猜你真正的意图更像是:

void add(linkedList *list, int newValue)
{
    link *temp = list->head;
    while (temp->next != nullptr)
        temp = temp->next;
    link *node = new node;
    node->next = nullptr;
    node->value = newValue;
    temp->next = node;
}

然而,对于堆栈,在添加新项之前,您不需要(或不希望)遍历列表。

void add(linkedList *list, int newValue) {
    link *node = new link;
    node->next = list->head;
    node->value = newValue;
    list->head = node;
}

不过,和往常一样,在使用链表时要三思(如果你有任何选择的话)。至少根据我的经验,很少是一个真正有用的数据结构(尤其是在像这样存储小项目的情况下),在一个典型的64位实现中,每个节点都是一个32位int和一个64位指针,所以指针的空间是数据本身的两倍