用数组实现栈(C/C++)

 1 #include<cstdio>
 2 #define MAX_SIZE 101
 3 //全局变量
 4 int a[MAX_SIZE];
 5 int top = -1;
 6 //压栈
 7 void Push(int n) {
 8     if (top == MAX_SIZE) {
 9         printf("error:the stack is overfiow!\n");
10         return;
11     }
12     a[++top] = n;
13 }
14 //出栈
15 void Pop() {
16     if (top == -1) {
17         printf("error:the stack is empty!\n");
18         return;
19     }
20     top--;
21 }
22 //返回栈顶元素
23 int Top() {
24     return a[top];
25 }
26 //判断栈是否为空
27 int isEmpty() {
28     if (top == -1) return 1;
29     return 0;
30 }
31 void print() {
32     printf("stack:");
33     for (int i = 0; i <= top; ++i) { //i <= top 刚开始写,没写等于,就出现了奇奇怪怪的结果
34         printf("%d ", a[i]);
35     }
36     printf("\n");
37 }
38 
39 int main() {
40     Push(7); print();
41     Push(4); print();
42     Push(8); print();
43     Push(1); print();
44     Pop(); print();
45     Push(9); print();
46 }

用C++实现

 1 #include<iostream>
 2 using namespace std;
 3 #define MAX_SIZE 101
 4 
 5 class Stack
 6 {
 7 private:
 8     int a[MAX_SIZE];
 9     int top;
10 public:
11     Stack()
12     {
13         top = -1;
14     }
15     void Push(int n) {
16         if (top == MAX_SIZE - 1) {
17             cout << "error , the stack is overflow" << endl;
18             return;
19         }
20         a[++top] = n;
21     }
22     void Pop() {
23         if (top == -1) {
24             cout << "error,the stack is empty!" << endl;
25             return;
26         }
27         top--;
28     }
29     int Top() {
30         return a[top];
31     }
32     int isEmpty() {
33         if (top == -1) return 1;
34         return 0;
35     }
36     void print() {
37         cout << "stack:";
38         for (int i = 0; i <= top; ++i) {
39             cout << a[i] << " ";
40         }
41         cout << endl;
42     }
43 };
44 
45 int main()
46 {
47     Stack s;
48     s.Push(7); s.print();
49     s.Push(4); s.print();
50     s.Push(8); s.print();
51     s.Push(1); s.print();
52     s.Pop(); s.print();
53     s.Push(9); s.print();
54 }

 

posted @ 2021-10-06 16:44  越菜越自信  阅读(337)  评论(1)    收藏  举报