【问题标题】:How to print a stack using arrays in c++ [closed]如何在 C++ 中使用数组打印堆栈 [关闭]
【发布时间】:2014-09-16 15:32:52
【问题描述】:

我已经添加了所有必需的功能 - 例如。推送、弹出和打印 - 在我的程序中,但无法在控制台屏幕上打印堆栈输出。我创建了三个单独的文件,其中包含类、函数和主文件。我想知道我在堆栈中插入的元素是否已成功插入,因此我需要打印更新后的堆栈。

stack.h

#ifndef Stack_H
#define Stack_H

using namespace std;

class Stack{
private: 
//int const capacity=50;
int stack[50];

int count;
int top;
int maxitem;

 public:  //this is where the functions go
 Stack();//constructor
 void Push(int data);
 void Pop(int delData);
 void PrintStack();
 };


#endif 

stack.cpp

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <vector>
#include <string>
#include "Stack.h"

using namespace std;

Stack::Stack()
{
    top=-1;
};

void Stack::Push(int data){
    top++;
    cin>>data;
    stack[top]=data;
    count++;
    cout<<"inserted succefully :"<<data<<endl;
}

void Stack::Pop(int item)
{
 if(top<0){
 cout<<"stack is empty";
            }
 else{
     item=stack[top];
     top--;

    cout<<"The deleted elememt is: "<<item<<endl;
     }
}


void Stack::PrintStack()
{
    if (top<0)
    {
        cout<<"Stack is empty ";
    }
    for(int i =top; i<0; i--)
    {
        cout<<"STACK IS "<<stack[i]<<"  "<<endl;
    }
}

main.cpp

#include <cstdlib>
#include <iostream>
#include <stack>
#include "Stack.h"

using namespace std;


int main()
{
    Stack R;
    int ele;
    int data;
    cout<<"enter the maximum elements in stack "<<endl;
     cin>>ele;
    cout<<endl<<"now enter the elements in stack "<<endl;


    for(int data=0; data<ele; data++){
    R.Push(data);

    R.PrintStack();
    }


    R.Pop(item);
    R.PrintStack();//stack after deletion of element


    system("pause");
}

【问题讨论】:

  • for (int i = 0; i &lt; top; ++i) cout &lt;&lt; stack[i] &lt;&lt; endl;怎么样
  • for (int i = top - 1; i &gt;= 0; --i) cout &lt;&lt; stack[i] &lt;&lt; endl;
  • I want to know that the elements I am inserting in the stack are successfully inserted 为什么不直接使用调试器?
  • 问题出在哪里?

标签: c++ stack


【解决方案1】:

例如函数可以这样定义

void PrintStack()
{
   for ( int i = top; i >= 0; --i ) std::cout << stack[i] << ' ';
}

考虑到函数 Pop 没有意义。至少应该声明为

 void Pop(int &delData);

【讨论】:

    【解决方案2】:

    我想知道我在堆栈中插入的元素是否已成功插入,因此我需要打印更新后的堆栈。

    堆栈容器是一个后进先出容器适配器,让您只能直接*访问后部元素(称为顶部)。当您编写自己的 Stack 课程时,请记住这一点。如果要确保实际插入了值,请实现一个 top() 函数,该函数返回 stack[top] 处的值。在每个push() 之后检查top()

    *注意 - 在std::stack 的标准实现中,您可以编写一个适配器来访问底层容器c

    【讨论】:

      猜你喜欢
      • 2012-11-26
      • 2020-07-06
      • 2010-09-23
      • 1970-01-01
      • 2016-07-05
      • 2020-08-28
      • 1970-01-01
      • 2013-12-07
      • 1970-01-01
      相关资源
      最近更新 更多