C++数据结构错误输出(链表)

C++ data structures wrong output (linked lists)

#include <iostream>
#include <cstdlib>

using namespace std;

typedef struct node{
    int size;
    char* name;
    node* next;
}node;

void insertnodes( node** arrayhead , int index , node* ptr){

    index = index - 1 ;
    while ( index--){

        *arrayhead = (*arrayhead)->next;
    }
    (*arrayhead)->next = new node; 
    (*arrayhead)->next = ptr;   
}


int main(){
    int n = 4;
    node *A[n] ;

    for ( int i = 0 ; i < n ; i++){
        A[i] = NULL ;
    }

    A[0] = new node; 

    A[0]->size = 10;
    A[0]->name = new char;
    A[0]->name = "gunna";
    A[0]->next = NULL;
    //cout << A[0]->name << endl;


    node* ptr = new node ;
    ptr->size = 10;
    ptr->name = new char;
    ptr->name = "param";
    ptr->next = NULL;


    insertnodes(&A[0] , 1 , ptr);

    node* ptrr = new node ;
    ptrr->size = 10;
    ptrr->name = new char;
    ptrr->name = "sidd";
    ptrr->next = NULL;
    insertnodes(&A[0] , 2 , ptrr);

    cout << A[0]->name << endl;
    cout << A[0]->next->name;



}

它应该打印 "gunna" 和 "param" 。

但它给出 "param" 和 "sidd" 作为输出。

我不知道我哪里错了。我已经尝试了很多东西,但我仍然感到困惑 请帮助... 我正在使用代码块来编译这个程序..

在您的 insertnodes() 中,您正在传递一个 双指针 node** arrayhead,因此,通过稍后取消引用,您将覆盖 [=] 的当前值14=] 指针,稍后将导致程序内存泄漏。

您应该做的是创建一个临时变量 node* tmp,您将在 index 减少时更改该变量。然后,您不需要为下一个指针分配一个新节点,因为 您已经有一个要附加的指针,如 next.

固定代码如下所示:

void insertnodes(node** arrayhead, int index, node* ptr) {
    index = index - 1;
    node* tmp = *arrayhead;
    while (index--) {
        tmp = tmp->next;
    }
    tmp->next = ptr;
}

编辑: 这完全没用:

int n = 4;
node *A[n] ;

for ( int i = 0 ; i < n ; i++){
    A[i] = NULL ;
}

创建链表只需要一个节点(例如链表头)。


但是因为这是一个链表,你真的不需要传递索引。您所需要的只是一个 head,您可以对其进行迭代,直到找到 node->next,这将是 NULL - 这是您需要插入新节点的地方(这就是它的方式通常完成)。