[c/cpp]: user stack - test
1. code
1 #include <cstdio>
2
3
4 #define STACKSIZE 100
5
6
7 struct stack {
8 int index;
9 int e[STACKSIZE];
10 };
11
12
13 void push(struct stack *s, int x)
14 {
15 if ( s->index < STACKSIZE && s->index >= 0) {
16 s->e[s->index] = x;
17 (s->index)++;
18 printf("[push]#\tpush(%d),\tpush_e[%d] := %d\n", x, s->index, s->e[s->index-1]);
19 } else {
20 perror("[push]#\tstack overflow");
21 }
22 }
23
24
25 void pop(struct stack *s, int *x)
26 {
27 if ( s->index < STACKSIZE && s->index >= 0) {
28 *x= s->e[s->index-1];
29 (s->index)--;
30 printf("[pop]#\tpop(%d), rest_e[%d] := %d\n", *x, s->index, s->e[s->index-1]);
31 } else {
32 perror("[pop]#\tstack has reached bottom");
33 }
34 }
35
36
37 void stack_loop(struct stack *s)
38 {
39 for (int i=0; i < s->index+1; i++) {
40 printf("[stack]#\te[%d]\t:=\t%d\n", i, s->e[i]);
41 }
42 }
43
44
45 int main(int argc, char *argv[], char *envp[])
46 {
47 int x;
48 int *p = &x;
49
50 struct stack s;
51 s = { .index=0 };
52
53 push(&s, 100);
54 push(&s, 200);
55 push(&s, 300);
56 push(&s, 400);
57 pop(&s, p);
58 push(&s, 500); // e[4]
59 push(&s, 600); // e[5]
60 pop(&s, p);
61 pop(&s, p);
62
63 stack_loop(&s);
64
65 return 0;
66 }
2. execute
[push]# push(100), push_e[1] := 100
[push]# push(200), push_e[2] := 200
[push]# push(300), push_e[3] := 300
[push]# push(400), push_e[4] := 400
[pop]# pop(400), rest_e[3] := 300
[push]# push(500), push_e[4] := 500
[push]# push(600), push_e[5] := 600
[pop]# pop(600), rest_e[4] := 500
[pop]# pop(500), rest_e[3] := 300
[stack]# e[0] := 100
[stack]# e[1] := 200
[stack]# e[2] := 300
[stack]# e[3] := 500
g++ -std=c++20 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
3. reference
1 cpp online - https://coliru.stacked-crooked.com/
本文由 lnlidawei 原创、整理、转载,本文来自于【博客园】; 整理和转载的文章的版权归属于【原创作者】; 转载或引用时请【保留文章的来源信息】:https://www.cnblogs.com/lnlidawei/p/18551530