数组栈

数组实现栈。

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
// 数组栈.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

#define MAX_SIZE 20
typedef int ElemType;
struct Node
{
ElemType data[MAX_SIZE];
int index;
Node()
{
index = 0;
}
};
struct Stack
{
Node top;
void InitStack()
{
for (int i = 0; i < MAX_SIZE; i++)
{
top.data[i] = rand() % MAX_SIZE + 1;
top.index = i;
}
}
void Push(int value)

{
if (top.index == MAX_SIZE - 1) exit(OVERFLOW);
top.data[top.index] = value;
top.index++;
}
int Pop()
{
if (top.index == 0) return -1;
return top.data[top.index--];
}
void TraverseStack()
{
int temp = top.index;
while (temp >= 0)
{
cout << top.data[temp--] << " ";
}
cout << endl;
//cout << top.index;
}
};
int main()
{
srand(time(NULL));
Stack s;
s.InitStack();
s.TraverseStack();
return 0;
}