C++ Program to Show working of Singly linked list

In computer science, a linked list is a data structure consisting of a group of nodes which together represent a sequence. Under the simplest form, each node is composed of a data and a reference (in other words, a link) to the next node in the sequence; more complex variants add additional links. This structure allows for efficient insertion or removal of elements from any position in the sequence.


                                                                           
 For more visit : http://en.wikipedia.org/wiki/Linked_list .





#include<iostream.h>
#include<conio.h>
struct node
{
int info;
node *ptr;
}*list;
void add(int item)
{
node *tem=new node;
tem->info=item;
tem->ptr=list;
list=tem;
cout<<"\nItem Added";
}
void remove(int item)
{
if(list==NULL)
{
cout<<"\nUnder flow :List is empty";
return;
}
node *tem=list;
node *ltem;
ltem->ptr=list;
while(tem!=NULL)
{
if(tem->info==item)
{
      ltem->ptr=tem->ptr;
      delete tem;
      cout<<"\nItem Deleted";
      return;
}
ltem=tem;
tem=tem->ptr;

}
cout<<"\nItem not found";
}
void show()
{
node *tem=list;
cout<<"\nList Item :";
while(tem!=NULL)
{
cout<<" "<<tem->info;
tem=tem->ptr;
}
}
void main()
{
clrscr();
int op;
int item;
while(op!=4)
{
cout<<"\nSelect Option\n1.add\n2.remove\n3.show\n4.exit\n";
cin>>op;
switch(op)
{
case 1:
cout<<"\nEnter the item to add : ";
cin>>item;
add(item);
break;
case 2:
cout<<"\nEnter the item to remove : ";
cin>>item;
remove(item);
break;
case 3:
show();
break;
case 4:
cout<<"Press any key to exit";
break;
default:
cout<<"Invalid";

}
getch();
}
}

0 comments:

Post a Comment