>x; while(x!=-99) { temp=new node(); temp->"> >x; while(x!=-99) { temp=new node(); temp->">

Linked List In CPP

#include<iostream>
#include<conio.h>
#include<stdio.h>
#include<ctype.h>
using namespace std;
class node
{
int data;
node*next;
public:
node *creatlist()
{
node*head,*tail, *temp;
int x;
head=NULL;
cout<<"Enter number(-99 to stop):";
cin>>x;
while(x!=-99)
{
temp=new node();
temp->data=x;
temp->next=NULL;
if(head==NULL)
{
head=tail=temp;
}
else
{
tail->next=temp;
tail=temp;
}
cout<<"enter value(-99 to stop)";
cin>>x;
}
return head;
}

void traverse(node*head)
{
node*p=head;
while(p!=NULL)
{
cout<<p->data<<"->";
p=p->next;
}
cout<<"\b"<<char(12)<<endl;
}

void searchnode(node*head,int srch)
{

node*p=head;
while(p!=NULL)
{

if(srch==p->data)
{

cout<<endl<<p->data<<" found\n";
{

break;
}
}
p=p->next;
}

if(p==NULL)
{
cout<<"\nnot found\n";
}

}



node *inserthead(node*head,int x)
{
node *tmp;
if(head==NULL)
{
cout<<"empty list";
}
else
{
tmp=new node();
tmp->data=x;
tmp->next=head;
head=tmp;
}
return head;
}
node *deletehead(node*head)
{
     
node*p=head;
if(head==NULL)
{
cout<<"empty list";
}
else
{
 head=p->next;
 delete(p);
 }
 return head;
}
node* inserttail(node*head,int x)
{
      node *tmp;
node*p=head;
if(head==NULL)
{
              cout<<"empty list";
              }
              else
              {
while(p->next!=NULL)
{
p=p->next;
}
tmp=new node();
tmp->data=x;
tmp->next=NULL;
p->next=tmp;
}

return head;
}
node*deletebefore(node*head,int srch)
{
node *p,*q;
p=head;
q=head->next;
while(q!=NULL)
{
if(q->next->data==srch)
{
break;
}
p=p->next; q=q->next;
}
if(q!=NULL)
{
p->next=q->next;
delete(q);
}
else
{
cout<<"Delete error";
}
return head;
}

};
int main()
{
int ch,srch,x;
char cnt;
node singly;
node*head;
do{
cout<<"1.for creatlist"<<endl<<"2.for traverse"<<endl<<"3.for search"<<endl<<"4. head insert"<<endl<<"5.delete head"<<endl<<"6.for insert tail"<<endl<<"7 for deletebefore"<<endl;
cout<<"enter your choice\n";
cin>>ch;

if(ch==1)
{
head=singly.creatlist();
}
else if(ch==2)
{
singly.traverse(head);
}
else if(ch==3)
{
cout<<"enter srch value";
cin>>srch;
singly.searchnode(head,srch);	
}
else if(ch==4)
{
cout<<"enter value for insert ";
cin>>x;
head=singly.inserthead(head,x);	
}
else if(ch==5)
{
cout<<"delete head";
head=singly.deletehead(head);

}
else if(ch==6)
{
     cout<<"insert new value for tail : ";
     cin>>x;
     head=singly.inserttail(head,x);
 }
 else if(ch==7)
 {
 cout<<"enter srch value";
 cin>>srch;

 head=singly.deletebefore(head,srch);
}
fflush(stdin);
cout<<"do you want to continue then press (y/n) : ";
cin>>cnt;
}
while(toupper(cnt)=='Y');


getch();
}



Leave a Reply