//Program to create a Linked List and to insert and delete elements by value
#include <iostream>
#include <cstdlib>
using namespace std;
struct node
{
int val;
struct node *next;
};
struct node *temp,*stemp,*ttemp,*first;
void Insert(int item)
{
temp= new node;
temp->val = item ;
temp->next= NULL ;
if(first==NULL)
{
first=temp;
}
else
{
stemp = first;
while(stemp->next!=NULL)
{
stemp=stemp->next;
}
stemp->next=temp;
}
cout<<"\nELEMENT INSERTED: "<<item;
}
void Delete(int item)
{
bool found=false;
if(first==NULL)
{
cout<<"\nLINKED LIST IS EMPTY!";
}
else
{
ttemp=stemp=first;
while(stemp->next!=NULL)
{
if(stemp->val==item)
{
found=true;
break;
}
ttemp=stemp;
stemp=stemp->next;
}
if(found)
{
if(stemp->next != NULL)
{
ttemp->next=stemp->next;
stemp->next=NULL;
}
else
{
ttemp->next=NULL;
stemp->next=NULL;
}
delete stemp;
cout<<"\nELEMENT DELETED!";
}
else
{
cout<<"\nELEMENT NOT FOUND!";
}
}
}
void Display()
{
if(first==NULL)
{
cout<<"\nLINKED LIST IS EMPTY\n";
}
else
{
stemp = first;
cout<<"\n\nLINKED LIST\n";
while(stemp!=NULL)
{
cout<<stemp->val<<" ";
stemp=stemp->next;
}
cout<<endl;
}
}
int main()
{
Insert(1);
Insert(2);
Insert(3);
Display();
Delete(2);
Display();
Insert(5);
Display();
return 0;
}
OUTPUT
1 comments :
commentsthank you good luck articel
Reply