为什么节点添加不正确?为什么反向打印? (单链表)

时间:2019-04-24 23:41:04

标签: c pointers linked-list segmentation-fault 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]--

2 个答案:

答案 0 :(得分:2)

此功能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;
    }

答案 1 :(得分: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;
    }

希望这会有所帮助。