数组模拟栈
有了单链表的基础,自己就能想出如何模拟栈:
设置一个栈顶指针变量t,保存在数组的0号位置,指向栈顶元素的位置,这样:
初始化为0,表示空栈;
入栈:先赋值,然后t++;
出栈:t- -;
判空就是看栈顶指针是否为0;
输出栈顶元素就是输出stk[t]
.
此外,数组是死的,人是活的。我们也可以新设置int变量,保存指针,而不放在数组0号位置;我们可以默认指针指向元素的下一个位置,只不过入栈时,是先赋值后移动指针;我们可以…所以栈的模板代码需要留意栈顶指针的含义,不要生搬硬套。
.
.
此外,学习yxc的代码风格,如此简洁
#include <iostream>
using namespace std;
const int N = 100010;
int m;
int stk[N], tt;
int main()
{
cin >> m;
while (m -- )
{
string op;
int x;
cin >> op;
if (op == "push")
{
cin >> x;
stk[ ++ tt] = x;
}
else if (op == "pop") tt -- ;
else if (op == "empty") cout << (tt ? "NO" : "YES") << endl;
else cout << stk[tt] << endl;
}
return 0;
}