【发布时间】:2017-02-06 13:48:51
【问题描述】:
这是推送功能。
void push(struct node **head)
{
struct node *temp;
temp = new node;
cout<<"enter the value";
cin>>temp->data;
temp->link=NULL;
if(*head==NULL)
{
*head=new node;
*head=temp;
}
else{
temp->link=*head;
*head=temp;
}
}
这就是我所说的推送。
struct node *start=NULL;
push(&start);
这是节点
struct node{
int data;
struct node *link;
};
现在的问题是:我认为列表没有更新。开始始终保持为空。不知道为什么。
编辑:
void display(struct node **head)
{
struct node *temp;
temp=*head;
if(*head==NULL){
cout<<"\nthe head is NULL\n";
}
while(temp!=NULL)
{
cout<<temp->data;
temp=temp->link;
}
}
int main() {
struct node *start=NULL;
push(&start);
push(&start);
push(&start);
push(&start);
push(&start);
display(&start);
return 0;
}
输入:
1
2
3
4
5
现在显示出来的应该是 5 4 3 2 1 但有一些错误。
【问题讨论】:
-
如果只有一种方法可以避免使用指针模拟传递引用的 C 厌恶。如果只有 C++ 有 true 引用。这将是一个值得考虑的功能,是吗? :-)
-
可能不是你的问题,但
*head=new node;是多余的。 -
minimal reproducible example 会增加答案的可能性和质量。
-
@SamarYadav 因为无论如何你都在下一行分配了
temp。分配的内存泄露了。
标签: c++ pointers linked-list stack