如何在c++中使用数组打印堆栈

How to print a stack using arrays in c++

本文关键字:数组 打印 堆栈 c++      更新时间:2023-10-16

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

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");
}

例如,可以这样定义函数

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

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

 void Pop(int &delData);

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

Stack Container是一个后进先出的容器适配器,只允许你直接访问back元素(也就是top)。当您编写自己的Stack类时,请记住这一点。如果你想确保你的值被实际插入,实现一个top()函数返回stack[top]处的值。每个push()后检查top()

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