C 中的按/POP堆栈类程序

Push/pop stack class program in C++?

本文关键字:堆栈 程序 POP      更新时间:2023-10-16

我已经编写并修改了C 书中的示例代码,以推出/弹出数字从堆栈类中推出。这是我理解的基本问题。这是代码。

//stakarray.cpp
//a stack as a class
#include <iostream>
using namespace std;
class Stack
{
  private:
    enum { MAX = 10 };
    //int MAX=10;
    int st[MAX];
    int top;
  public:
    Stack()
    { top=0; }
    void push(int var)
    { st[++top]=var; } //increments stack, input var
    int pop()
    { return st[top--]; } //returns var, decrements stack
    void show(int var)
    { cout << st[var]<< endl; }
};
int main()
{
  //some stack operations
  int i;
  Stack s1;
  s1.push(11);
  s1.push(22);
  cout<<"1: "<<s1.pop()<<endl; //22
  cout<<"2: "<<s1.pop()<<endl; //11
  s1.push(33);
  s1.push(44);
  s1.push(55);
  s1.push(66);
  for (i=0; i<= 10 ; i++)
  {
   cout<< "s1[" << i << "]= ";
   s1.show(i); 
  }
  return 0;
}

该程序的输出给出

1: 22
2: 11
s1[0]= 2
s1[1]= 33
s1[2]= 44
s1[3]= 55
s1[4]= 66
s1[5]= 0
s1[6]= 0
s1[7]= 0
s1[8]= 4196896
s1[9]= 0
s1[10]= 4

为什么S1 [0] = 2,S1 [8] = 4196896,S1 [10] = 4?是否有任何方法可以从私有访问最大值,或者我必须将其定义在类中的其他位置(不用为全局变量或Main()的一部分)?

元素0永远不会使用,因为在推送中,您使用插入前( top)而不是插入后(top )。

您的堆栈一次最多有4个元素,因此索引4之后的所有元素都有未定义的内容(即S1 [5] ... S1 [10]中的随机垃圾)。

在您的代码中,在设置值之前,您用预注++top递增了顶部。因此,顶部将转到1,然后您将设置s1[1]=33。如果您切换到收入后top++,则在设置s[0]=33之后您的计数器变量top将增加。

//stakarray.cpp
//a stack as a class
#include <iostream>
using namespace std;
class Stack
{
  private:
    enum { MAX = 10 };
    //int MAX=10;
    int st[MAX];
    int top;
  public:
    Stack()
    { top=0; }
    void push(int var)
    { st[top++]=var; } //increments stack, input var
    int pop()
    { return st[top--]; } //returns var, decrements stack
    void show(int var)
    { cout << st[var]<< endl; }
};
int main()
{
  //some stack operations
  int i;
  Stack s1;
  s1.push(11);
  s1.push(22);
  cout<<"1: "<<s1.pop()<<endl; //22
  cout<<"2: "<<s1.pop()<<endl; //11
  s1.push(33);
  s1.push(44);
  s1.push(55);
  s1.push(66);
  for (i=0; i<= 10 ; i++)
  {
   cout<< "s1[" << i << "]= ";
   s1.show(i); 
  }
  return 0;
}