C++列表功能不损坏
我正在尝试创建一个程序,让我在列表的尾部添加元素,然后打印它们。这不会给我一个错误,但他什么也没做。我在做什么错?
#include<iostream>
using namespace std;
struct lista{
int val;
lista *next;
};
typedef lista* ptr_lista;
void tail_add(ptr_lista head, int valore){
if(head=NULL){
head=new lista;
head->val=valore;
head->next=NULL;
} else {
ptr_lista p=head;
while(p->next!=NULL){
p=p->next;
}
p->next=new lista;
p->next->val=valore;
p->next->next=NULL;
}
}
void print(ptr_lista p){
while(p!=NULL){
cout<<p->val<< " ";
p=p->next;
}
}
int main(){
ptr_lista m;
tail_add(m,5);
tail_add(m,6);
print(m);
}
I'm tryin to create a program that let me add elements in tail of a list and then prints them. It doesn't give me an error but he doesn't do anything. What am I doing wrong ?
#include<iostream>
using namespace std;
struct lista{
int val;
lista *next;
};
typedef lista* ptr_lista;
void tail_add(ptr_lista head, int valore){
if(head=NULL){
head=new lista;
head->val=valore;
head->next=NULL;
} else {
ptr_lista p=head;
while(p->next!=NULL){
p=p->next;
}
p->next=new lista;
p->next->val=valore;
p->next->next=NULL;
}
}
void print(ptr_lista p){
while(p!=NULL){
cout<<p->val<< " ";
p=p->next;
}
}
int main(){
ptr_lista m;
tail_add(m,5);
tail_add(m,6);
print(m);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于初学者,指针
m
尚未初始化,并且具有不确定的值,您需要初始化其
函数通过值接受指针,
因此在功能中更改参数
head
对原始指针
m
在MAIN中声明的效果。您需要将参数声明为对指针的引用,
定义函数,以下方式
引入别名不是一个好
注意
主意
可以通过以下方式
,要为指针 声明函数参数的声明
print
,因为它不会更改列表的节点。For starters the pointer
m
is not initialized and has an indeterminate valueYou need to initialize it
The function accepts the pointer by value
So changing the parameter
head
within the function likehas no effect on the original pointer
m
declared in main.You need to declare the parameter as a reference to the pointer
The function can be defined the following way
Pay attention to that it is not a good idea to introduce an alias for a pointer like
For example if you will write
then it means
not
that is required for the declaration of the parameter of the function
print
because it does not change nodes of the list.