Professional
Professional
ASSIGNMENT-4
Course: BTECH(CSE)
Section: B1
}
dequeue(q1,f1,r1);
(*f1)=(*f2);
(*r1)=(*r2);
(*f2)=-1;
(*r2)=-1;
}
void display(int q1[],int f1,int r1)
{
for(int i=f1;i<=r1;i++){
printf("%d ",q1[i]);
}
printf("\n");
}
int main()
{
int f1=-1,f2=-1,r1=-1,r2=-1;
int n;
printf("Enter the size:");
scanf("%d",&n);
int q1[n],q2[n];
push(q1,&f1,&r1,50,n);
push(q1,&f1,&r1,40,n);
push(q1,&f1,&r1,30,n);
push(q1,&f1,&r1,20,n);
push(q1,&f1,&r1,10,n);
printf("Elements of the stack is:\n");
display(q1,f1,r1);
pop(q1,q2,&f1,&f2,&r1,&r2,n);
printf("Stack after popping:");
display(q1,f1,r1);
return 0;
}
Method 2.
Push: Costly
Pop: Optimal
Algorithm
Push
Step1. Enqueue elements at Queue2
Step2. Dequeue elements of Queue1
Enqueue to Queue2
Step3. Swap the Queue’s references
Pop
Step1. Dequeue from Queue1
#include<stdio.h>
#include<string.h>
void swap(int*str1, int*str2)
{
int *temp = str1;
str1 = str2;
str2 = temp;
}
void enqueue(int q[],int*f,int*r,int x)
{
q[(*r)++]=x;
(*f)=-1;
}
int dequeue(int q1[],int*f1,int*r1)
{
int t;
t=q1[(*r1)++];
return t;
}
void push(int q1[],int*f1,int*r1,int x,int n)
{
if((*r1)==n-1)
{
printf("Stack is full");
}
else
{
enqueue(q1,f1,r1,x);
}
}
void pop(int q1[],int q2[],int*f1,int*f2,int*r1,int*r2,int n)
{
int i=0;
if((*r1)!=-1)
{
printf("Stack is empty");
return;
}
else
{
while(i<n-1)
{
int t=dequeue(q1,f1,r1);
enqueue(q2,f2,r2,t);
i++;
}
int t=dequeue(q1,f1,r1);
enqueue(q2,f2,r2,t);
swap(q1,q2);
(*f1)=(*f2);
(*r1)=(*r2);
(*f2)=-1;
(*r2)=-1;
}
}
void display(int q1[],int f1,int r1)
{
for(int i=f1;i<r1;i++)
{
printf("%d ",q1[i]);
}
printf("\n");
}
int main()
{
int f1=-1,f2=-1,r1=-1,r2=-1;
int n;
printf("Enter the size:");
scanf("%d",&n);
int q1[n],q2[n];
push(q1,&f1,&r1,11,n);
push(q1,&f1,&r1,12,n);
push(q1,&f1,&r1,13,n);
push(q1,&f1,&r1,14,n);
printf("The elements of the stack:");
display(q1,f1,r1);
pop(q1,q2,&f1,&f2,&r1,&r2,n);
printf("The stack after popping:");
display(q1,f1,r1);
return 0;
}
Question: Implement stack using two Queues
With using STL
Algorithm
Use class Queue to declare two queues
Push
Step1. Push element into Queue1
Pop
Step1. Dequeue (n-1) elements from Queue1
And Enqueue to Queue2
Step2. Dequeue nth element from Queue1
and return it.
Step3. Swap the references of Queue1 and
Queue2
#include<iostream>
#include<queue>
using namespace std;
queue<int>t=q1;
while(!t.empty())
{
cout<<t.front()<<" ";
t.pop();
}
}
int main()
{
queue<int>q1;
queue<int>q2;
push(1,q1);
push(2,q1);
push(3,q1);
push(4,q1);
push(5,q1);
push(6,q1);
cout<<"Elements in the stack is:";
display(q1);
cout<<endl<<"Popped element:"<<pop(q1,q2)<<endl;
cout<<"Popped element is:"<<pop(q1,q2)<<endl;
cout<<"After popping the stack looks like:";
display(q1);
return 0;
}