Insertion and Deletion (at beg, in-between & at end) in Singly Linked List


/*Insert and delete the node at beginning , in-between and middle of singly linked list*/



#include<iostream>
#include<stdlib.h>
using namespace std;

class node
{
int data;
node *next;
public:
void insert(node *);
void dis(node *);
void ins(node *);
void insertbeg(node *);
void insertend(node *);
void delb(node *);
void dele(node *);
void delein(node *);
};

void node::insertend(node *head)
{
//head=new node;
node *t;
t=new node;
cout<<"Enter data";
cin>>t->data;
t->next=NULL;
node* temp;
temp=head;
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=t;
}


void node::insertbeg(node *head)
{
node *t;
t=new node;
cout<<"Enter data";
cin>>t->data;
t->next=NULL;
node* temp;
temp=head;

if(head->next==NULL)
{
head->next=t;
}
else
{
t->next=temp->next;
temp->next=t;
}
}



void node::ins(node *head)
{
int n;
node *nw;
nw=new node;
cout<<"\nEnter value before you want to insert\n";
cin>>n;
cout<<"\nEnter data you want to insert\n";
cin>>nw->data;
nw->next=NULL;
node *temp;
temp=head;
while(temp->next->data!=n)
{
temp=temp->next;
}
nw->next=temp->next;
temp->next=nw;
}


void node::dis(node *head)
{
node *temp;
temp=head->next;
cout<<"(";
while(temp!=NULL)
{
cout<<temp->data<<",";
temp=temp->next;
}
cout<<")";
}

void node::delb(node * head)
{
node *temp;
temp=head->next;
if(head->next==NULL)
{
cout<<"\nCan't Delete\n";
}
else
{

head->next=temp->next;
delete temp;
}
}


void node::dele(node *head)
{
node *t;
t=head;
while(t->next->next!=NULL)
t=t->next;

t->next=NULL;
delete t->next;
}


void node:: delein(node *head)
{
node *t;
int value;
t=head;
cout<<"\nEnter the node you have to delete\n";
cin>>value;
while(t->next->data!=value)
t=t->next;
node *k;
k=t->next;
t->next=k->next;
delete k;
}

main()
{
int ch;
node n;
node* head;
head=new node;
while(1)
{
cout<<"\n1.Display \n2.insert at beginning \n3.Insert at in between \n4.Insert at end  \n5.delete beg\n6.delete end \n7.delete inbetween \n8.exit";
cout<<"\nEnter choice\n";
cin>>ch;
switch(ch)
{
case 1:
n.dis(head);
break;

case 2:
n.insertbeg(head);
break;
case 3:
n.ins(head);
break;
case 4:
n.insertend(head);
break;

case 5:
n.delb(head);
break;

case 6:
n.dele(head);
break;

case 7:
n.delein(head);
break;
case 8: exit(0);
}
}
}

Post a Comment

0 Comments