-
Notifications
You must be signed in to change notification settings - Fork 2
/
two_stacks_using_single_array.cpp
164 lines (135 loc) · 2.47 KB
/
two_stacks_using_single_array.cpp
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
/****************************************************************************
File name: two_stacks_using_single_array.cpp
Author: babajr
*****************************************************************************/
/*
Implement two stacks using the single array.
*/
#include <stdio.h>
#include <stdlib.h>
struct two_stacks
{
int top1;
int top2;
int size;
int *arr;
};
typedef struct two_stacks stacks;
stacks st;
/*
Initialise the two_stacks structure.
*/
void create(int size)
{
st.top1 = -1;
st.top2 = size;
st.size = size;
st.arr = (int *)calloc(sizeof(int), st.size);
}
// void create(int size)
// {
// st->top1 = -1;
// st->top2 = size;
// st->size = size;
// st->arr = (int *)malloc(sizeof(int) * st->size);
// }
/*
API to push element in the stack 1.
*/
void push_stack1(int val)
{
// check if stack is full
if(st.top1 < st.top2 - 1) // space of atleast one element should be empty.
{
st.top1++;
st.arr[st.top1] = val;
}
else
{
printf("STACK OVERFLOW\n");
return;
}
}
/*
API to pop element from the stack 1.
*/
int pop_stack1()
{
int x = -1;
// check if stack is empty
if(st.top1 >= 0)
{
x = st.arr[st.top1];
st.top1++;
}
else
{
printf("STACK UNDERFLOW\n");
}
return x;
}
/*
API to push element in the stack 2.
*/
void push_stack2(int val)
{
// check if stack is full
if(st.top1 < st.top2 - 1) // space of atleast one element should be empty.
{
st.top2--;
st.arr[st.top2] = val;
}
else
{
printf("STACK OVERFLOW\n");
return;
}
}
/*
API to pop element from the stack 2.
*/
int pop_stack2()
{
int x = -1;
// check if stack is empty
if(st.top2 < st.size)
{
x = st.arr[st.top2];
st.top2--;
}
else
{
printf("STACK UNDERFLOW\n");
}
return x;
}
/*
API to display elements of the stack.
*/
void display()
{
printf("STACK 1: \n");
for(int i = 0; i <= st.top1; i++)
printf("%d\t", st.arr[i]);
printf("\n");
printf("STACK 2: \n");
for(int i = st.size - 1; i >= st.top2; i--)
printf("%d\t", st.arr[i]);
printf("\n");
}
int main(void)
{
// stacks st;
// create(&st, 5);
create(5);
push_stack1(1);
push_stack1(2);
push_stack1(3);
pop_stack1();
display();
push_stack2(4);
push_stack2(5);
pop_stack2();
display();
return 0;
}