write program link list insert midle and delete ?
#include<iostream>
using namespace std;
struct Node
{
int data;
Node* next;
};
class LinkList
{
Node* head=NULL;
public:
void AddNode(int value)
{
struct Node* temp=new Node;
temp->data=value;
temp->next=NULL;
if(head==NULL)
head=temp;
else
{
Node* p=head;
while(p->next!=NULL)p=p->next;
p->next=temp;
}
}
void InsertMiddle(int value)
{
struct Node* temp=new Node;
temp->data=value;
temp->next=NULL;
if(head==NULL)
head=temp;
else
{
int len=0;
Node* p=head;
while(p!=NULL)//count elements
{
len++;
p=p->next;
}
int count;
if(len%2==0)count=len/2;
else count=len/2+1;
p=head;
int i=1;
while(i<count)//find middle
{
i++;
p=p->next;
}
//insert to middle
temp->next=p->next;
p->next=temp;
}
}
void Delete(int value)
{
Node* p=head;
Node* prev=head;
if(p->data==value)
{
head=p->next;
cout<<"\nValue "<<p->data<<" has been deleted";
delete p;
return;
}
while(p->data!=value&&p->next!=NULL)
{
prev=p;
p=p->next;
}
if(p->next==NULL)
cout<<"Value not found";
else
{
prev->next=p->next;
cout<<"\nValue "<<p->data<<" has been deleted";
delete p;
}
}
void DeleteMid()
{
int len=0;
Node* p=head;
Node* prev=head;
if(p->next==NULL||p->next->next==NULL)
{
head=p->next;
cout<<"\nValue "<<p->data<<" has been deleted";
delete p;
return;
}
while(p!=NULL)//count elements
{
len++;
p=p->next;
}
int count;
if(len%2==0)count=len/2;
else count=len/2+1;
p=head;
int i=1;
while(i<count)//find middle
{
i++;
prev=p;
p=p->next;
}
//delete from middle
prev->next=p->next;
cout<<"\nValue "<<p->data<<" has been deleted";
delete p;
}
void ListDisplay()
{
Node* temp=head;
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
}
};
int main()
{
LinkList l;
l.AddNode(10);
l.AddNode(15);
l.AddNode(20);
l.AddNode(25);
l.AddNode(30);
l.AddNode(35);
l.ListDisplay();
l.InsertMiddle(40);
cout<<endl;
l.ListDisplay();
l.Delete(20);
cout<<endl;
l.ListDisplay();
l.DeleteMid();
cout<<endl;
l.ListDisplay();
l.DeleteMid();
cout<<endl;
l.ListDisplay();
}
Comments
Leave a comment