Reputation: 13
Why is the argument for display in main() start and not newptr? Also, how does np->next=save; and np=np->next work in their respective functions? I am very new to the concept of linked lists. Any help would be much appreciated.
#include<iostream>
using namespace::std;
struct node
{
int info;
node *next;
} *start,*newptr,*save,*ptr;
node * create_new_Node(int);
void insert_beg(node *);
void display(node*);
int main()
{
start=NULL;
int inf; char ch='y';
while(ch=='y'||ch=='Y')
{
system("cls");
cout<<"Enter information for the new node : \n";
cin>>inf;
cout<<"\nCreating new node";
system("pause");
newptr=create_new_Node(inf);
if(newptr!=NULL)
{
cout<<"New node created successfully.";
system("pause");
}
else
{
cout<<"\aNot enough memory =S ...\n";
exit(1);
}
cout<<"Now inserting this node to the beginning of the list :";
system("pause");
insert_beg(newptr);
cout<<"Now the list is : ";
display(start);
cout<<"Press Y or y to enter more nodes :::: ";
cin>>ch;
}
return 0;
}
node * create_new_Node(int n)
{
ptr=new node;
ptr->info=n;
ptr->next=NULL;
return ptr;
}
void insert_beg(node *np)
{
if(start==NULL)
{
start=np;
}
else
{
save=start;
start=np;
np->next=save;
}
}
void display(node * np)
{
while(np!=NULL)
{
cout<<np->info<<" -> ";
np=np->next;
}
}
Upvotes: 0
Views: 53
Reputation: 29344
Why is the argument for display in main() start and not newptr?
Because start
is the head pointer in your linked list and always points to the first node in the linked list. To display the linked list, you have to start from the first node and that first node is pointed to by start
pointer.
how does np->next=save; and np=np->next work in their respective functions?
np->next=save;
it means that next
pointer of node np
should point to the node which is pointed to by save
pointer.
np=np->next;
it is being used in display
function to iterate over your linked list.
Upvotes: 0
Reputation: 1018
in insert_beg, the pointer to start is changed to the new start position which is the newly inserted node.
in my opinion, pointer operations are better to undrstand in a graphical model..
Upvotes: 1