为什么节点没有正确添加,为什么它是反向打印的? (单链表)

Why aren't nodes adding properly and why is it printing in reverse? (singly linked list)

已解决

这个问题也可以通过在添加新节点后将头部复制到另一个变量中来解决。 一个更合乎逻辑的解决方案是按照答案所说的去做。



我正在练习一个简单的链表实现,也想更多地探索指针。为什么我的代码没有正确添加节点?

typedef struct Node{

    int info;

    struct Node* next;

}Node;

void createList(Node** node, int info){

        *node = calloc(1, sizeof(Node));
        (*node)->info = info;
        (*node)->next = NULL;

}
Node* newNode(int info)
{
    Node* newNode;
    newNode = calloc(1, sizeof(Node));
    newNode->info = info;
    newNode->next = NULL;

    return newNode;
}

void addNode(Node** node, int info){
    int adaugat = 0;


    if(*node == NULL){

        createList(node, info);
        adaugat = 1; 
    }

    if(adaugat == 0)
    {
        Node **aux = node;
        while((*aux)->next != NULL)
        {
            *aux = (*aux)->next;
        }
        (*aux)->next = newNode(info);
        adaugat = 1;
    }

}
void printList(Node* node){
    int i = 1;
    Node* aux;
    aux = node;
    while(aux != NULL)
    {
        printf("%d_[%d]--",i, aux->info );
        i++;
        aux = aux->next;
    }
}
int main(int argc, char const *argv[])
{
    Node *nod = NULL;
    int key = 5;

    createList(&nod, key);

    addNode(&nod, 5);
    addNode(&nod, 3);
    addNode(&nod, 4);
    addNode(&nod, 1);

    printList(nod);

    return 0;
}

我曾尝试在 main() 中使用指针和函数调用输入来回移动,但我得到的只是更多警告和段错误。 main() 的输出是 1_[4]--2_[1]-- 而应该是

1_[5]--2_[3]--3_[4]--4_[1]--

在这个函数片段中 addNode

if(adaugat == 0)
    {
        Node **aux = node;
        while((*aux)->next != NULL)
        {
            *aux = (*aux)->next;
        }
        (*aux)->next = newNode(info);
        adaugat = 1;
    }

更准确地说,在行 *aux = (*aux)->next; 上,由于 Node ** aux,您在遍历列表的同时移动了列表。因此,您的列表看起来总是有两个元素。

如果要在列表的末尾添加元素,则必须遍历列表而不修改它,即

if(adaugat == 0)
    {
        Node *aux = *node;
        while(aux->next != NULL)
        {
            aux = aux->next;
        }
        aux->next = newNode(info);
        adaugat = 1;
    }

问题出在下面的代码块

    if(adaugat == 0)
    {
        Node **aux = node;
        while((*aux)->next != NULL)
        {
            *aux = (*aux)->next;
        }
        (*aux)->next = newNode(info);
        adaugat = 1;
    }

变量 node 没有被解除引用,这里没有必要使用双指针。将该部分更改为以下内容将为您提供所需的输出...


    if(adaugat == 0)
    {
        Node *aux = *node;
        while(aux->next != NULL)
        {
            aux = aux->next;
        }
        aux->next = newNode(info);
        adaugat = 1;
    }

希望对您有所帮助。