首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >堆栈操作中的top升级是如何进行的

堆栈操作中的top升级是如何进行的
EN

Stack Overflow用户
提问于 2020-10-22 16:32:03
回答 1查看 35关注 0票数 0

我是编程的初学者。我在极客上为极客找到了这段堆栈代码。我很困惑,像push()之后的pop()这样的操作怎么会知道top已经升级了。例如,在这段代码中,在三次push()操作之后,top现在是2(即top=2)。现在调用下一个函数pop()。这个函数如何知道top的最终状态现在是2。我有点困惑。

代码语言:javascript
复制
/* 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;
}
EN

回答 1

Stack Overflow用户

发布于 2020-10-22 16:40:21

push操作在此处修改top类成员:

代码语言:javascript
复制
++top

在这条线内

代码语言:javascript
复制
a[++top] = x;  

另外,pop操作修改行中的top

代码语言:javascript
复制
int x = a[top--];

当另一个操作需要top字段时,它读取实际值。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64478288

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档