Saturday 4 November 2017

Insertion and Deletion of alternate nodes in Header Linklist in C++

// please like my facebook page www.facebook.com/playwithcplus 
// My fb profile www.facebook.com/mujtaba.aamir1

#include<bits/stdc++.h>   // used to include all header standard C++ header file
#include<conio.h>
using namespace std;
struct node
{
int info;
node *link;
node *prev;

};

void insertFirst(node **start,int data)
{
node *temp=new node;
temp->info=data;
temp->link=NULL;
*start=temp;
temp->prev=NULL;
}
void insertEnd(node *start,int data)
{

node *temp=new node;
while(start->link!=NULL)
{
start=start->link;
}

temp->info=data;
start->link=temp;
temp->prev=start;
temp->link=NULL;
}
void deleteAlternate(node *start)
{
node *curr=start;
node *nexttonext;
while(curr!=NULL&&curr->link!=NULL&&curr->link->link!=NULL)
{
curr->link->link->prev=curr->link->prev;
nexttonext=curr->link->link;
delete(curr->link);
curr->link=nexttonext;
curr=curr->link;


}
if(curr->link->link==NULL)
{
delete(curr->link);
curr->link=NULL;
}

}

void disp(node *start)
{
node *last;
cout<<"\nIn Forward Direction: ";
while(start!=NULL)
{
cout<<"->"<<start->info;
last=start;
start=start->link;
}
cout<<"\nIn Backward Direction: ";
while(last!=NULL)
{
cout<<"->"<<last->info;
last=last->prev;
}

}
main()
{

node *start=NULL;
insertFirst(&start,1);
insertEnd(start,2);
insertEnd(start,3);
insertEnd(start,4);
insertEnd(start,5);
insertEnd(start,6);
disp(start);
deleteAlternate(start);
disp(start);
}

No comments:

Post a Comment

Amazon1Ads