我是编程的初学者。我在极客上为极客找到了这段堆栈代码。我很困惑,像push()之后的pop()这样的操作怎么会知道top已经升级了。例如,在这段代码中,在三次push()操作之后,top现在是2(即top=2)。现在调用下一个函数pop()。这个函数如何知道top的最终状态现在是2。我有点困惑。
/* C++ program to implement basic stack operations */
#include <bits/stdc++.h>
using namespace std;
#define MAX 1000
class Stack {
int top = -1;
public:
int a[MAX]; // Maximum size of Stack
bool push(int x);
int pop();
int peek();
bool isEmpty();
};
bool Stack::push(int x) {
if (top >= (MAX - 1)) {
cout << "Stack Overflow";
return false;
} else {
a[++top] = x;
cout << x << " pushed into stack\n";
return true;
}
}
int Stack::pop() {
if (top < 0) {
cout << "Stack Underflow";
return 0;
} else {
int x = a[top--];
return x;
}
}
int Stack::peek() {
if (top < 0) {
cout << "Stack is Empty";
return 0;
} else {
int x = a[top];
return x;
}
}
bool Stack::isEmpty() { return (top < 0); }
// Driver program to test above functions
int main() {
class Stack s;
s.push(10);
s.push(20);
cout << s.peek();
cout << s.pop() << " Popped from stack\n";
cout << s.peek();
return 0;
}发布于 2020-10-22 16:40:21
push操作在此处修改top类成员:
++top在这条线内
a[++top] = x; 另外,pop操作修改行中的top
int x = a[top--];当另一个操作需要top字段时,它读取实际值。
https://stackoverflow.com/questions/64478288
复制相似问题