-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack_by_queue.c
171 lines (158 loc) · 2.75 KB
/
stack_by_queue.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
// implement stacks using queue
#include <stdio.h>
#include <stdlib.h>
#define max 5
struct queue
{
int size;
int f;
int r;
int *arr;
};
struct stack
{
struct queue *q1;
struct queue *q2;
};
struct queue *createQueue()
{
struct queue *q = (struct queue *)malloc(sizeof(struct queue));
if (!q)
{
return NULL;
}
q->size = max;
q->f = q->r = -1;
q->arr = (int *)malloc(max * sizeof(int));
if (!q->arr)
{
return NULL;
}
return q;
}
struct stack *createStack()
{
struct stack *s = (struct stack *)malloc(sizeof(struct stack));
if (!s)
{
return NULL;
}
s->q1 = createQueue();
if (!s->q1)
{
return NULL;
}
s->q2 = createQueue();
if (!s->q2)
{
return NULL;
}
return s;
}
int queueIsEmpty(struct queue *q)
{
return (q->f == -1);
}
int queueIsFull(struct queue *q)
{
return ((q->r + 1) % q->size == q->f);
}
int stackIsEmpty(struct stack *s)
{
return (queueIsEmpty(s->q2) && queueIsEmpty(s->q1));
}
int stackIsFull(struct stack *s)
{
return (queueIsFull(s->q1) || queueIsFull(s->q2));
}
void enqueue(struct queue *q, int data)
{
if (queueIsFull(q))
{
// printf("Queue overflow\n");
return;
}
else
{
q->r = (q->r + 1) % q->size;
q->arr[q->r] = data;
if (q->f == -1)
{
q->f = q->r;
}
}
}
int dequeue(struct queue *q)
{
if (queueIsEmpty(q))
{
// printf("Queue underflow\n");
return 0;
}
else
{
int data;
data = q->arr[q->f];
if (q->f == q->r)
{
q->f = q->r = -1;
}
else
{
q->f = (q->f + 1) % q->size;
}
return data;
}
}
void push(struct stack *s, int data)
{
if (stackIsFull(s))
{
printf("Stack overflow\n");
}
else
{
if (queueIsEmpty(s->q1))
{
enqueue(s->q2, data);
}
else
{
enqueue(s->q1, data);
}
}
}
int pop(struct stack *s)
{
if (stackIsEmpty(s))
{
printf("Stack underflow");
return 0;
}
else
{
if (queueIsEmpty(s->q2))
{
for (int i = s->q1->f; i < s->q1->r; i++)
{
int data = dequeue(s->q1);
enqueue(s->q2, data);
}
return dequeue(s->q1);
}
if (queueIsEmpty(s->q1))
{
for (int i = s->q2->f; i < s->q2->r; i++)
{
int data = dequeue(s->q2);
enqueue(s->q1, data);
}
return dequeue(s->q2);
}
}
}
int main()
{
struct stack *s = createStack();
return 0;
}