Skip to content

Commit b06fcee

Browse files
authored
栈的基本操作
1 parent fdbcad7 commit b06fcee

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

Stack.cpp

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
#include <cstdio>
2+
#include <cstring>
3+
4+
#define ELEMENT_COUNT 100000
5+
6+
using namespace std;
7+
8+
// Requirement: every element in stack must be positive.
9+
// Otherwise, M[0] should be set to -INF.
10+
int S[ELEMENT_COUNT], M[ELEMENT_COUNT];
11+
int sp = 1;
12+
13+
void push(int x)
14+
{
15+
S[sp] = x;
16+
if (x > M[sp - 1])
17+
{
18+
M[sp] = x;
19+
}
20+
else
21+
{
22+
M[sp] = M[sp - 1];
23+
}
24+
sp++;
25+
}
26+
27+
int pop()
28+
{
29+
return S[--sp];
30+
}
31+
32+
bool empty()
33+
{
34+
return sp == 1;
35+
}
36+
37+
int get_max()
38+
{
39+
return M[sp - 1];
40+
}
41+
42+
int main()
43+
{
44+
while (true)
45+
{
46+
char o[10];
47+
int a;
48+
scanf(" %s", o);
49+
if (strcmp(o, "push") == 0)
50+
{
51+
scanf("%d", &a);
52+
push(a);
53+
}
54+
else if (strcmp(o, "pop") == 0)
55+
{
56+
printf("%d\n", pop());
57+
}
58+
else if (strcmp(o, "getmax") == 0)
59+
{
60+
printf("%d\n", get_max());
61+
}
62+
else if (strcmp(o, "abort") == 0)
63+
{
64+
return 0;
65+
}
66+
else
67+
{
68+
printf("No such instruction.\n");
69+
}
70+
}
71+
72+
return 0;
73+
}

0 commit comments

Comments
 (0)