Tuesday, September 19, 2017

Linked List program (creation,insertion,deletion from beginning,delete by value,search)

#include<iostream>
using namespace std;
#include<conio.h>
#include<stdlib.h>
struct node
{
int info;
node *next;      
}*start=NULL;

void creation();
void insertion(node *);
void deletion_beg(node *);
void display(node *);
void deletion(node *);
void search(node *);

int main()
{
int choice;
if(start==NULL)
    {
creation();
    }  

while(1)
    {
cout<<"\n**** Enter choice: ****"  <<endl;
cout<<"1 : Insertion"  <<endl;
cout<<"2 : Deletion"  <<endl;
cout<<"3 : Display"  <<endl;
cout<<"4 : Exit"  <<endl;
cout<<"5 : Deletion by value "  <<endl;
cout<<"6 : search"<<endl;

cin>>choice;
switch(choice)
            {
case 1:
insertion(start);
break;                    
case 2:
deletion_beg(start);
break;                    
case 3:
display(start);
break;
case 4:
exit(1);
break;
case 5:
deletion(start);
break;
case 6:
search(start);
break;

default:
cout<<"Wrong choice..." <<endl;        
            }
    }
getch();
return 0;  
}

void creation()
{
start = new node;
cout<<"Enter data-value for 1st node: ";
cin>>start->info;
start->next = NULL;
}
void insertion(node *p)
{
while(p->next!=NULL)
{p=p->next;
}
node *temp=new node;
cout<<"enter data value";
cin>>temp->info;
temp->next=NULL;
p->next=temp;

}
void display(node *p)
{
cout<<"elements are: ";
while(p!=NULL)
{
cout<<p->info<<"---->";
p=p->next;
}
cout<<"NULL"<<endl;
}

void search(node *p)
{
int item,i;
cout<<"enter the no. to search ";
cin>>item;
while(p!=NULL)
{
 i++;
if(p->info==item)
{
cout<<"item found at "<<i<<endl;
}
p=p->next;
}
}

void deletion_beg(node *p)
{
int loc;
node *pp=NULL;
p=start;
if(p==NULL)
{
cout<<"underflow ";
}
else
{
start=p->next;
delete p;
}
}

void deletion(node *p)
{
p=start;
int item;
struct node *ptr,*ptrp;
if(p->next==NULL)
{
cout<<"underflow ";
}
else
{
cout<<"enter the item to be deleted : ";
cin>>item;
ptr=start;
while((ptr->next!=NULL)&&(ptr->info!=item))
{
ptrp=ptr;
ptr=ptr->next;
}
if(ptr->info==item)
{
ptrp->next=ptr->next;
free(ptr);
cout<<"deleted "<<item;
}
else
{
cout<<"not found";
}
}
}