//堆栈,数组实现
#include<iostream>
using namespace std;
#define Maxsize 100
class stack
{
public:
int data[Maxsize];
int top = -1; //保存栈顶下标值
};
int pop(stack*ptrl); //出栈
void push(stack*ptrl,int x);//进栈
int main()
{
stack l;
stack*ptrl = &l;
int i,m;
for (i = 0; i < 10; i++){
cin >> m; //十个数进堆栈
push(ptrl, m);
}
for (i = 0; i < 10;i++)
cout<<pop(ptrl)<<" "; //倒序出堆栈
cout << endl;
return 0;
}
void push(stack*ptrl,int x)
{
if (ptrl->top == Maxsize - 1){ //判断堆栈是否已满
cout << "堆栈已满" << endl;
return;
}
ptrl->top++;
ptrl->data[ptrl->top] = x; //进栈
}
int pop(stack*ptrl)
{
if (ptrl->top == -1){
cout << "堆栈已空" << endl;
return 0;
}
ptrl->top--;
return ptrl->data[ptrl->top + 1]; //出堆栈
}
时间: 2024-10-12 15:38:46