Assignment 3
Assignment 3
ASSIGNMENT-3
Course: BTECH(CSE)
Section: B1
Algorithm
Enqueue
Step1. While Stack1 is empty push every element into
Stack 2
Step2. Push element to Stack1
Step3. Again, push back everything to Stack1 one
Dequeue
Step1. If Stack1 is empty then, Queue is empty
Step2. Otherwise, Pop Stack1
//impelementing Queue using Stack
//enqueue O(n)
//dequeue O(1)
#include<stdio.h>
int n=5;
void Push(int s[],int*top,int x)
{
s[++(*top)]=x;
}
int Pop(int s[],int*top)
{
int x=s[*top];
(*top)--;
return x;
}
void enqueue(int s1[],int s2[],int*top1,int*top2,int x)
{
if((*top1)==n-1)
{
printf("Queue is full");
}
else
{
while((*top1)!=-1)
{
int t=Pop(s1,top1);
Push(s2,top2,t);
}
Push(s1,top1,x);
while((*top2)!=-1)
{
int t=Pop(s2,top2); //Push(Pop(s2,&top2))
Push(s1,top1,t);
}
}
}
int dequeue(int s[],int*top)
{
int x=s[*top];
(*top)--;
return x;
}
void Display(int s[],int top)
{
while(top!=-1)
{
printf("%d ",s[top]);
top--;
}
}
int main()
{
int s1[n],s2[n];
int top1=-1,top2=-1;
enqueue(s1,s2,&top1,&top2,10);
enqueue(s1,s2,&top1,&top2,15);
enqueue(s1,s2,&top1,&top2,20);
enqueue(s1,s2,&top1,&top2,25);
enqueue(s1,s2,&top1,&top2,30);
Display(s1,top1);
int x= dequeue(s1,&top1);
printf("deleted valuie is:%d \n",x);
Display(s1,top1);
return 0;
}
Method 2
Enqueue: More Costly
Dequeue: Costly
Algorithm
Enqueue
Step1. If top1!=Size-1 then Push into Stack 1
Dequeue
Step1. If Stack1 is not empty, push every element into
Stack 2
Step2. Pop Stack2
Step3. Push every element back to Stack1
//impelementation of queue using stack
//enqueue O(1)
//dequeue O(n)
#include<stdio.h>
int N=10;
int count=0;
void Push(int S1[],int*top,int x)
{
(*top)++;
S1[*top]=x;
}
int Pop(int S1[],int*top1)
{
int t=S1[*top1];
(*top1)--;
return t;
}
void enqueue(int s1[],int*top1,int x)
{
Push(s1,top1,x);
}
void dequeue(int s1[],int s2[],int *top1,int *top2)
{
if((*top1)==-1)
{
printf("Queue is empty");
}
else
{
while((*top1)!=-1)
{
int a=Pop(s1,top1); //Push2(Pop1)
Push(s2,top2,a);
}
int b=Pop(s2,top2);
printf("\nelement that is dequeued is:%d\n",b);
count--;
while((*top2!=-1))
{
int t =Pop(s2,top2);
Push(s1,top1,t);
}
}
}
void display(int s[],int top)
{
for(int i=0;i<=top;i++)
{
printf("%d ",s[i]);
}
}
int main()
{
int S1[N],S2[N];
int top1=-1,top2=-1;
enqueue(S1,&top1,60);
enqueue(S1,&top1,70);
enqueue(S1,&top1,80);
display(S1,top1);
dequeue(S1,S2,&top1,&top2);
enqueue(S1,&top1,90);
display(S1,top1);
return 0;
}