Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
#include<bits/stdc++.h>
using namespace std;

struct doublyqueue {
int d;
doublyqueue* next=NULL;
doublyqueue* prev=NULL;
};
doublyqueue *front=NULL;
doublyqueue *rear=NULL;
doublyqueue *mid=NULL;
// f->null r->null mid =null
// f->1<-r mid=1 i.e when changed from even to odd by push mid updated
// f->1>2><r mid =1 odd to ev no ch
//f->1>2>3<r mid=2 i.e mid=mid->next when changed to odd and n!=1
//del 1 i.e deque => mid= 2 i.e mid= mid->prev i.e


// now check for delete mid ex only 1 then mid=null
//if 1 2 mid=1 and delmid=> mid=m->next;
// if 1 2 3 mid= 2 del mid => mid=m->prev;
// 1 2 3 4 m=2 del 2 => 1 3 4 mid = 3 i.e m->next;
// i.e size reduced and if new size is odd => m=m->next
int size=0;
void push(int data)
{
// push in a queue => insertion at rear
doublyqueue *temp= new doublyqueue();
temp->d=data;
size++;

// base case if queue is empty
if(front==rear && !front)// front=r=NULL
{
front=temp;
rear=temp;
mid=temp;
}
else
{
// one element
rear->next=temp;
temp->prev=rear;
rear=temp;
if(size%2!=0)// changed from even to odd
{
mid=mid->next;
}

}
}
void pop()
{
// delete at front
int d;

if(front==rear && !front) // if empty
{
mid=NULL;

return;
//return -1;
}
else if( front == rear)
{ size--;
d= front->d;
front=NULL;
rear=front;
mid=front;
}
else
{ size--;
d= front->d;
front=front->next;
front->prev=NULL;
if(size%2==0)
{
mid=mid->prev;
}
}
return;
//return d;
}
void displayfromfront(doublyqueue *f)
{
while(f!=NULL)
{
cout<<f->d<<" ";
f=f->next;
}
}
void printmiddata()
{
if(mid!=NULL)
cout<< mid->d<<endl;
else
cout<< -1<<endl;
}
void printtopdata()
{
int i= front!=NULL ? front->d : -1;
cout<<i<<endl;
}
void deletemid()
{
size--;
if(front==rear && !front)
{
return ;
}
else if(front==rear)
{
front=NULL;
rear=NULL;

}
else
{
doublyqueue* p =mid->prev;
doublyqueue* f =mid->next;
p->next=p->next->next;
f->prev=p;
mid->prev=NULL;
mid->next=NULL;
if(size%2==0)
{
mid=p;
}
else
{
mid= f;
}
}
}

int main(){

int n; // elements to push
cin>>n;
while(n--){
int d;
cin>>d;
push(d);
}
int t; // quries
cin>>t;
while(t--){

cin>>n;
if(n==1){
int x;
cin>>x;
push(x);
}
else if(n==2){
pop();
}
else if(n==3){

deletemid();
}
else if(n==4){
printtopdata();
}
else if(n==5){
printmiddata();
}
else if(n==6)
{
displayfromfront(front);
}
}
}