-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSharedStack.cpp
More file actions
151 lines (147 loc) · 2.72 KB
/
Copy pathSharedStack.cpp
File metadata and controls
151 lines (147 loc) · 2.72 KB
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
#include <iostream>
using namespace std;
#define MaxSize 10
typedef struct sharedStack
{
int top1;
int top2;
int data[MaxSize];
} SharedStack;
void Init(SharedStack &S)
{
int i = 0;
for (i = 0; i < MaxSize; i++)
{
S.data[i] = 0;
}
S.top1 = -1;
S.top2 = MaxSize;
cout << "Init……" << endl;
}
bool Destroy(SharedStack &S)
{
S.top1 = -1;
S.top2 = MaxSize;
cout << "Destroy……" << endl;
return true;
}
bool StackEmpty(SharedStack S, int order)
{
if (order == 1)
{
if (S.top1 == -1)
{
cout << "Empty" << endl;
}
return (S.top1 == -1);
}
if (order == 2)
{
if (S.top2 == MaxSize)
{
cout << "Empty" << endl;
}
return (S.top2 == MaxSize);
}
}
bool StackFull(SharedStack S)
{
if ((S.top1 + 1) == S.top2)
{
cout << "Stack is Full" << endl;
return true;
}
return false;
}
bool push(SharedStack &S, int order, int e)
{
if (order == 1)
{
if (StackFull(S))
{
return false;
}
S.data[++(S.top1)] = e;
cout << "push:" << e << endl;
return true;
}
if (order == 2)
{
if (StackFull(S))
{
return false;
}
S.data[--(S.top2)] = e;
cout << "push:" << e << endl;
return true;
}
}
bool pop(SharedStack &S, int order, int &popElem)
{
if (order == 1)
{
if (StackEmpty(S, order))
{
return false;
}
popElem = S.data[S.top1--];
cout << "pop:" << popElem << endl;
return true;
}
if (order == 2)
{
if (StackEmpty(S, order))
{
return false;
}
popElem = S.data[S.top2++];
cout << "pop:" << popElem << endl;
return true;
}
}
bool GetTop(SharedStack S, int order, int &topElem)
{
if (order == 1)
{
if (StackEmpty(S, order))
{
return false;
}
topElem = S.data[S.top1];
cout << "GET:" << topElem << endl;
return true;
}
if (order == 2)
{
if (StackEmpty(S, order))
{
return false;
}
topElem = S.data[S.top2];
cout << "GET:" << topElem << endl;
return true;
}
}
int main()
{
SharedStack S;
Init(S);
StackEmpty(S, 1);
StackEmpty(S, 2);
StackFull(S);
int i = 0;
for (i = 0; i < MaxSize - 5; i++)
{
push(S, 1, i);
push(S, 2, i);
}
int popElem;
GetTop(S, 1, popElem);
GetTop(S, 2, popElem);
for (i = 0; i < MaxSize - 5; i++)
{
pop(S, 1, popElem);
pop(S, 2, popElem);
}
Destroy(S);
}