-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stack.cpp
90 lines (82 loc) · 1.48 KB
/
Stack.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
#include <iostream>
#define MaxSize 100
using namespace std;
typedef struct
{
char data[MaxSize];
int top;
}Stack;
void InitStack(Stack * S)
{
S->top = -1;
}
int Empty(Stack * S)
{
return S->top < 0 ? 1 : 0;
}
int Full(Stack * S)
{
return S->top >= MaxSize - 1 ? 1 : 0;
}
int Push(Stack * S, char elem)
{
if(Full(S))
{
cout << "Error!The stack is full!" << endl;
return 0;
}
S->top++;
S->data[S->top] = elem;
return 1;
}
int Pop(Stack * S, char * x)
{
if(Empty(S))
{
cout << "Error!The stack is empty!" << endl;
return 0;
}
*x = S->data[S->top];
S->top--;
return 1;
}
int GetTop(Stack * S, char * x)
{
if(Empty(S))
{
cout << "Error!The stack is empty!" << endl;
return 0;
}
*x = S->data[S->top];
return 1;
}
int main()
{
Stack S;
char e;
InitStack(&S);
cout << "栈";
if(Empty(&S))
cout << "空" << endl;
else
cout << "非空" << endl;
cout << " a进栈" << endl; Push(&S, 'a');
cout << " b进栈" << endl; Push(&S, 'b');
cout << " c进栈" << endl; Push(&S, 'c');
cout << " d进栈" << endl; Push(&S, 'd');
cout << " 栈";
if(Empty(&S))
cout << "空" << endl;
else
cout << "非空" << endl;
GetTop(&S, &e);
cout << "栈顶元素" << e << endl;
cout << "出栈次序:";
while(!Empty(&S))
{
Pop(&S, &e);
cout << e;
}
cout << endl;
return 0;
}