1
1
/*
2
2
Implement a queue using two stacks
3
3
4
+ It means ENQUEUE and DEQUEUE should use push and pop operations inside it.
5
+
4
6
If n elements are to be inserted on to a queue implemented using two stacks and m have to be deleted
5
7
Push Pop
6
8
Best case m+n 2m
@@ -11,39 +13,39 @@ Work Case 2n n+m
11
13
#include <stdlib.h>
12
14
#define MAX 50
13
15
14
- void push (int arr [],int data ,int * top ){
15
- if (* top == MAX - 1 ){
16
+ void push (int arr [],int data , int * ptr ){
17
+ if (* ptr == MAX - 1 ){
16
18
printf ("overflow\n" );
17
19
return ;
18
- }
19
- arr [++ * top ] = data ;
20
+ }
21
+ arr [++ ( * ptr )] = data ;
20
22
}
21
23
22
- void insert (int arr [],int data , int * top ){
23
- push (arr ,data ,top );
24
+ int pop (int arr [],int * ptr ){
25
+ if (* ptr == -1 ){
26
+ printf ("underflow\n" );
27
+ return -1 ;
28
+ }
29
+ int data = arr [(* ptr )-- ];
30
+ return data ;
24
31
}
25
32
26
- int pop (int arr [], int * top ){
27
- int data = arr [* top ];
28
- * top -- ;
29
- return data ;
33
+ void enqueue (int arr [],int data , int * top1 ){
34
+ push (arr ,data ,top1 );
30
35
}
31
36
32
- int delete (int arr2 [], int arr1 [],int * top2 , int * top1 ){
33
- int elm ;
34
- if (* top2 == -1 ){
35
- if (* top1 == -1 ){
36
- return -1 ; //this can be an error code
37
- }
37
+ int dequeue (int arr1 [], int arr2 [],int * top1 , int * top2 ){
38
+ int data , result ;
39
+ if (* top2 == -1 && * top1 == -1 ){
40
+ return -1 ;
38
41
}else {
39
- while (* top2 >= 0 ){
40
- int data = pop (arr2 , * top2 );
41
- * top2 -- ;
42
- push (arr1 ,data ,* top1 );
42
+ while (* top1 != -1 ){
43
+ data = pop (arr1 ,top1 );
44
+ push (arr2 ,data ,top2 );
43
45
}
44
- elm = pop (arr1 ,top1 );
45
- return elm ;
46
+ result = pop (arr2 ,top2 );
46
47
}
48
+ return result ;
47
49
}
48
50
49
51
int main (){
@@ -60,15 +62,14 @@ int main(){
60
62
switch (step ){
61
63
case 1 : printf ("enter element to be pushed\n" );
62
64
scanf ("%d" ,& elm );
63
- insert ( stack2 ,elm , & top2 );
65
+ enqueue ( stack1 ,elm , & top1 );
64
66
break ;
65
- case 2 : result = delete ( stack2 , stack1 ,& top2 ,& top1 );
66
- if (result == -1 ){
67
+ case 2 : result = dequeue ( stack1 , stack2 ,& top1 , & top2 );
68
+ if (result < 0 ){
67
69
printf ("already empty\n" );
68
70
}else {
69
- printf ("%d was popped\n" , result );
70
- }
71
-
71
+ printf ("%d was deleted\n" , result );
72
+ }
72
73
break ;
73
74
case 3 : exit (1 );
74
75
break ;
0 commit comments