【问题标题】:How does top upgrade in the stack operations栈顶操作如何升级
【发布时间】:2021-02-05 05:41:17
【问题描述】:

我是编程初学者。我在极客的极客上找到了这个堆栈代码。我很困惑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;
}

【问题讨论】:

  • 你的代码是C++,请不要标记其他不相关的语言。并且竞赛网站上的代码不是值得学习的好代码,它通常很糟糕而且只会显示坏习惯。如果您想学习 C++,请get some good books 阅读或参加几门课程。这也将帮助您了解代码如何跟踪变量及其值。

标签: c++ algorithm function stack


【解决方案1】:

push 操作在这里修改top 类成员:

++top

在这一行内

a[++top] = x;  

还有pop操作修改了top这一行

int x = a[top--];

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

【讨论】:

    猜你喜欢
    • 2015-07-31
    • 1970-01-01
    • 1970-01-01
    • 2018-05-08
    • 1970-01-01
    • 2017-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多