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);
}
For starters the pointer m
is not initialized and has an indeterminate value
ptr_lista m;
You need to initialize it
ptr_lista m = nullptr;
The function accepts the pointer by value
void tail_add(ptr_lista head, int valore){
So changing the parameter head
within the function like
head=new lista;
has no effect on the original pointer m
declared in main.
You need to declare the parameter as a reference to the pointer
void tail_add(ptr_lista &head, int valore){
The function can be defined the following way
void tail_add( ptr_lista &head, int valore )
{
ptr_lista new_lista_ptr = new lista { valore, nullptr };
if ( head == nullptr )
{
head = new_lista_ptr;
}
else
{
ptr_lista p = head;
while ( p->next ) p = p->next;
p->next = new_lista_ptr;
}
}
Pay attention to that it is not a good idea to introduce an alias for a pointer like
typedef lista* ptr_lista;
For example if you will write
const ptr_lista
then it means
lista * const
not
const lista *
that is required for the declaration of the parameter of the function print
because it does not change nodes of the list.