如果栈的默认 top 指针是-1,那么 top 始终指向栈顶的一个元素,如下图左边
如果栈的默认 top 指针是 0,那么 top 始终指向栈顶的上边(也就是新元素入栈后会被放到的位置),如下图右边
top 指向不同会导致入栈和出栈的逻辑有些区别
xxxxxxxxxx
131bool Push(SqStack &S, ElemType e) {
2 if(S.top==MaxSize-1)
3 return false;
4 S.data[++S.top] = e;
5 return true;
6}
7
8bool Pop(SqStack &S, ElemType &e) {
9 if(S.top == -1)
10 return false;
11 e = S.data[S.top--];
12 return true;
13}
xxxxxxxxxx
131bool Push(SqStack &S, ElemType e) {
2 if(S.top==MaxSize-1)
3 return false;
4 S.data[S.top++] = e;
5 return true;
6}
7
8bool Pop(SqStack &S, ElemType &e) {
9 if(S.top == -1)
10 return false;
11 e = S.data[--S.top];
12 return true;
13}
用 js 理解下 i++ 和 ++i 的区别