Linked List

#include<iostream.h>
#include<conio.h>
#include<malloc.h>

struct node
{
int data;
struct node *link;
};

int main()
{
clrscr();
struct node *newnode,*ptr,*pptr,*start;
int ch,count=0,pos;
start=NULL;

while(1)
{
//giving graphical view to linked list
clrscr();
count=0;
ptr=start;
while(ptr!=NULL)
{
cout<<"["<<ptr->data<<"]\n";
ptr=ptr->link;
count++;
}
cout<<"\n\nTotal "<<count<<" nodes\n\n";

cout<<"\n MENU\n______\n\n";
cout<<"1. Insert\n2. Delete\n0. EXIT\n\nchoice: ";
cin>>ch;
switch(ch)
{
case 1:
newnode=(node*)malloc(sizeof(node));
if(newnode==NULL)
{
cout<<"\nout of memory\n\npress any key to continue..";
getch();
break;
}
cout<<"\n\nInsertion\n__________\n\n";
cout<<"1. Insert at beginning\n2. Insert at position\n3. Insert at End\n\nchoice: ";
cin>>ch;
cout<<"\n\nEnter the data:\n";
cin>>newnode->data;

if(start==NULL)
{
start=newnode;
start->link=NULL;
ch=0;
}
switch(ch)
{
case 1://insert at begenning
newnode->link=start;
start=newnode;
break;

case 2://insert at position
pptr=ptr=start;
count=0;
cout<<"insert at position:\n";
cin>>pos;
if(pos==1)
{
newnode->link=start;
start=newnode;
break;
}
while(count!=pos-1&&ptr!=NULL)
{
count++;
pptr=ptr;
ptr=ptr->link;
}
newnode->link=ptr;
pptr->link=newnode;
break;


case 3://insert at end
ptr=start;
while(ptr->link!=NULL)
{
ptr=ptr->link;
}
ptr->link=newnode;
newnode->link=NULL;
break;

case 0:
break;

default:
cout<<"\nWrong choice...  Enter again\n";

}//end of switch for insertion
break;

case 2:
if(start==NULL)
{
cout<<"Underflow\n\nPress any key to  continue..";
getch();
break;
}
cout<<"\n\nDeletion\n__________\n\n";
cout<<"1. Delete from beginning\n2. Delete from position\n3. Delete from End\n\nchoice: ";
cin>>ch;
switch(ch)
{
case 1://delete from beginning
ptr=start;
start=start->link;
free(ptr);
break;

case 2://delete from position
pptr=ptr=start;
count=0;
cout<<"\nDelete from position:\n";
cin>>pos;
if(pos==1)
{
start=start->link;
free(ptr);
break;
}
while(count!=pos-1&&ptr!=NULL)
{
count++;
pptr=ptr;
ptr=ptr->link;
}
pptr->link=ptr->link;
free(ptr);
break;

case 3://delete from end
ptr=start;
while(ptr->link!=NULL)
{
pptr=ptr;
ptr=ptr->link;
}
pptr->link=NULL;
free(ptr);
break;

}//end of switch for deletion
break;

case 0://exit
//freeing all the memory before exit
while(start!=NULL)
{
ptr=start;
start=start->link;
free(ptr);
}
return 0;
}//end of switch
}//end of while
}//end  of main


Comments

Popular Posts