#include<iostream>
using namespace std;
class node{
public:
int data;
node* addr;.//it's address of the next node
node(int val){
data=val;
addr = NULL;
}
};
void addVal(node* &head, int val){
node *n=new node(val);
if (head==NULL){
head = n;
return;///<-WHY THIS?
}
node *p=head;
while(p->addr!=NULL){
p=p->addr;
}
p->addr=n;
return;
}
void display(node *head){
node *p=head;
while(p!=NULL){
cout<<p<<" "<<p->data<<" "<<p->addr<<endl;
p=p->addr;
}
}
int main(){
node *head=NULL;
addVal(head,1);
addVal(head,2);
addVal(head,3);
addVal(head,4);
addVal(head,5);
display(head);
return 0;
}
I was getting a blank terminal when I ran this without the return; inside of the if statement. Why is return necessary here? (I passed head's val by reference, so if I change it inside of the function the actual value would be affected as usual. But somehow it gets stuck without the return).
CodePudding user response:
If you do not return
this is what happens:
node *p=head; // p equals head which equals n
while(p->addr!=NULL){ // p->addr is NULL, this loop stops immediately
p=p->addr;
}
p->addr=n; // this assignes n to p's next ptr
return;
The use of many different names for the same thing can be a little confusing. You create a new node and the pointer to it is n
. This is the new head
. p
also points to this new head
.
Now addr
is the next node of head
.
If you do not return after creating the new head
and assigning the pointer to head
the function will continue to assing the pointer to the same node to head->addr
. You'd get a list with a head that has itself as the next node.
You could have observed this by using a debugger.