Monday 8 October 2018

Insertion, Deletion ,Searching at First ,Last , At Given Position in Linked List Implementation in C++

#include<bits/stdc++.h>
using namespace std;
struct node
{
node *link;
int data;
}*start=NULL;
// INSERTION INTO LINKED LIST
void insertNode(int data)
{
node *temp=new node;
temp->link=NULL;
temp->data=data;
if(start==NULL)
{
start=temp;
return;
}
else
{
node *ptr=start;
while(ptr->link!=NULL)
{
ptr=ptr->link;
}
ptr->link=temp;
}
}
void insertInBetween(int data,int search)
{
node *temp=new node;
temp->data=data;
temp->link=NULL;
node *ptr=start;
while(ptr->link!=NULL and ptr->data!=search)
ptr=ptr->link;
temp->link=ptr->link;
ptr->link=temp;
}
void insertFirst(int data)
{
node *temp=new node;
temp->data=data;
temp->link=start;
start=temp;
}
void insertInBetweenBefore(int data,int search)
{
node *prev=NULL,*ptr=start,*temp=new node;
temp->data=data;
while(ptr->link!=NULL and ptr->data!=search)
{
prev=ptr;
ptr=ptr->link;
}
temp->link=prev->link;
prev->link=temp;
}

// ?? VARIOUS LINKED LIST DELETION OPERATIONS ?? //
void deleteFirst()
{
node *ptr=start;
if(ptr->link==NULL)
start=NULL;
else
start=ptr->link;

delete(ptr);
}
void deleteAtPosition(int pos)
{
node *ptr=start;
node *prev=NULL;
int count=0;
while(ptr->link!=NULL and count!=pos)
{
prev=ptr;
count+=1;
ptr=ptr->link;
}
prev->link=ptr->link;
delete(ptr);
}

void deleteLast()
{
node *ptr=start,*prev=NULL;
while(ptr->link!=NULL)
{
prev=ptr;
ptr=ptr->link;
}
prev->link=NULL;
delete(ptr);
}

void disp()
{
node *ptr=start;
while(ptr!=NULL)
{
cout<<" -->"<<ptr->data;
ptr=ptr->link;
}
}

int main()
{
insertNode(10);
insertNode(20);
insertNode(30);
insertNode(40);
cout<<"BEFORE\n";
disp();
cout<<"\nINSERTION AFTER 30\n";
insertInBetween(35,30);
disp();
cout<<"\nINSERTION AT FIRST NODE\n";
insertFirst(5);
disp();
cout<<"\nINSERTION BEFORE 30\n";
insertInBetweenBefore(25,30);
disp();
cout<<"\nDELETING FIRST ELEMENT\n";
deleteFirst();
disp();
cout<<"\nDELETING AT GIVEN POSITION =3:\n";
deleteAtPosition(3);
disp();
cout<<"\nDELETING LAST ELEMENT:\n";
deleteLast();
disp();


}

No comments:

Post a Comment

Amazon1Ads