content=//adding a new node at any place in a linked list
//acording to users choice
#include%26lt;iostream.h%26gt;
#include%26lt;conio.h%26gt;
#include%26lt;string.h%26gt;
#include%26lt;process.h%26gt;
struct abc
{
char n[20];
int p;
abc *next;
};
void main()
{
clrscr();
int c=0,per;
abc *list,*start=NULL,*ptr,*prev;
char nm[20],flag;
cout%26lt;%26lt;"enter the name and percentage marks of five children ";
for(int i=0;i%26lt;=4;i++)
{
if(start==NULL)
{
ptr=new abc;
cout%26lt;%26lt;"enter the details :";
cin%26gt;%26gt;ptr-%26gt;n%26gt;%26gt;ptr-%26gt;p;
start=ptr;
prev=ptr; //start=ptr=prev
}
else //implemented 4 times
{
ptr=new abc;
cin%26gt;%26gt;ptr-%26gt;n%26gt;%26gt;ptr-%26gt;p;
prev-%26gt;next=ptr;
prev=prev-%26gt;next;
}
}
int ch;
cout%26lt;%26lt;"\n enter the choice where the record is to be inserted \n";
cout%26lt;%26lt;"\n 1. starting of the list ";
cout%26lt;%26lt;"\n 2. in between ";
cout%26lt;%26lt;"\n 3. at the end";
cin%26gt;%26gt;ch;
list=new abc;
cout%26lt;%26lt;"\n enter the name and percent of new student :";
cin%26gt;%26gt;list-%26gt;n%26gt;%26gt;list-%26gt;p;
if (ch==1)
{
list-%26gt;next=start;
start=list;//now making list the starting point
}
else if(ch==3)
{
ptr=start;
while(ptr!=NULL)
{prev=ptr;
ptr=ptr-%26gt;next;
}
prev-%26gt;next=list;
list-%26gt;next=NULL;
}
else
{
cout%26lt;%26lt;"\n enter the record number (2-4) after which the node is to be inserted";
cin%26gt;%26gt;c;
if (c==1 || c==5)
{
cout%26lt;%26lt;"sorry wrong no. entered ";
exit(0);
}
i=0 ;
//insert the node
ptr=start;
cout%26lt;%26lt;"\n"%26lt;%26lt;"the list is :\n";
cout%26lt;%26lt;"name percentage\n";
while(ptr!=NULL)
{
i++;
if (i==c)
{
list-%26gt;next=ptr-%26gt;next; //????????
ptr-%26gt;next=list; //?????????????
}
ptr=ptr-%26gt;next;
}
}
ptr=start;
// display all the records ;
while (ptr!=NULL)
{
cout%26lt;%26lt;ptr-%26gt;n%26lt;%26lt;" "%26lt;%26lt;ptr-%26gt;p;
ptr=ptr-%26gt;next;
cout%26lt;%26lt;"\n";
}
getch();
}
Can you plz explain me with this?
list points to the new structure.
ptr points to the structure after which you will place list
so
list-%26gt;next = the next structure of where you are inserting list.
ptr-%26gt;next = list.
It basically places (list) in between ptr and ptr-%26gt;next.
Reply:Those two lines are simply moving some pointers. What exactly do you need explaining? Why do you need another example - surely the one you have is just fine?
I would recommend going and searching the net for C tutorials and references, and reading up on pointer operations. It might also be worth your time learning about linked lists and how they work.
survey
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment