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

Linklist Structure (passing strucure pointer to a function )

本文关键字:结构 函数 指针 链表      更新时间:2023-10-16

我为链表做了一个结构,然后全局声明了它的指针,然后做了两个函数来添加节点和显示列表。当我在全局范围内声明结构指针时,一切都很好

但后来我在主函数中声明了指针,并根据需要更改了代码。但现在当我编译并运行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;

您可以点击下面的链接进行测试,您可能需要更新您的打印功能,以便不打印出当前为0的头值:

在线试用!

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