链表结构(将结构指针传递给函数)

Linklist Structure (passing strucure pointer to a function )

我做了一个link列表的结构体,然后全局声明了它的指针,然后做了两个添加节点和显示列表的函数。 当我全局声明结构指针时一切正常,

但后来我在主函数中声明了指针,并根据需要更改了代码。但是现在当我编译 运行 exe 时。它让我 xxxx.exe 停止工作!

Tldr:将结构指针传递给函数但它不起作用!

 #include<iostream>

 using namespace std;

 struct node {

 int data;
 node *adr;
 };


 void insertate(int n, struct node *h)
 {

    struct node *temp;
    temp = new node;
    temp->data=n;
    temp->adr=NULL;


    if(h==NULL)
    {   
        h=temp;    
    }

    else
    {
        struct node *q;
        q= new node;
        q=h;
        while(q->adr!=NULL)
        {
            q=q->adr;      
        }
        q->adr=temp;   

    } 

 }


 void  print(struct node *h)
 {

    struct node *c=h;
    while(c!=NULL)
    {
        cout<<c->data;
        c=c->adr;   
        cout<<endl;     
    }          
 }      


 int main()
 {   
    struct node *a;

    insertate(5,a);
    insertate(4,a);
    insertate(31,a);
    insertate(32,a);
    insertate(34,a);
    insertate(36,a);

    print(a);

    return 0;

 }  

首先在 main() 中分配您的头节点

struct node *a = new node;

然后尝试通过引用传递:

insertate(5, &a);

您还需要更新您的方法定义,而不是 *h 它将是 **h,如下所示:

#include <iostream>
using namespace std;

struct node {
  int data;
  node *adr;
};

void insertate(int n, struct node **h) {
  struct node *temp;
  temp = new node;
  temp->data=n;
  temp->adr=NULL;

  if(h==NULL) {
    *h=temp;
  }
  else
  {
    struct node *q;
    q= new node;
    q=*h;
    while(q->adr!=NULL)
    {
      q=q->adr;
    }
    q->adr=temp;
  }
}

void print(struct node **h)
{
  struct node *c=*h;
  while(c!=NULL)
  {
    cout<<c->data;
    c=c->adr;
    cout<<endl;
  }
}

int main() {
  struct node *a = new node;
  a->data = 0;      // Set this to initial head value
  a->adr = NULL;
  insertate(5, &a);
  insertate(4, &a);
  insertate(31, &a);
  insertate(32, &a);
  insertate(34, &a);
  insertate(36, &a);
  print(&a);
  return 0;
}

同样,当您在方法内部访问 h 时,因为它是指向指针的指针,您需要取消引用,因此请注意:

q = *h;

您可以点击下面的 link 进行测试,您可能需要更新您的打印功能,以便不打印出现在为 0 的 head 值:

Try it online!

这样我们就在main函数中使用new操作符在堆上分配了头指针。有些人给头指针一个虚拟变量,但在这种情况下,我认为在 main 函数中初始化更容易。现在我们有了一个指向堆中内存的指针,我们可以使用它的地址(又名 & 运算符)将它传递给我们的函数。这将创建一个指向其类型的指针 (**h) 的指针。就像常规指针一样,我们需要取消引用它才能访问它的值,这就是为什么我们在想要访问头指针时使用 *h 的原因。