1、作业要求
使用C++的类实现顺序栈。
2、实现过程
1)stack.h文件
#ifndef STACK_H
#define STACK_H
#define MAX 20
//定义顺序栈类
class Stack {
private:
int* data;
int top;
public:
//创建顺序栈
void stack_init();
//判空
bool stack_empty();
//入栈
void stack_push(int e);
//遍历栈
void stack_show();
//出栈
void stack_pop();
//销毁
void stack_delete();
};
#endif // STACK_H
2)stack.cpp文件
#include <iostream>
#include <stack.h>
using namespace std;
//申请空间
void Stack::stack_init() {
data = new int[MAX];
//初始化
top = -1;
}
//判空
bool Stack::stack_empty(){
return top == -1;
}
//入栈
void Stack::stack_push(int e){
//入栈,先加后压
top++;
data[top] = e;
cout << data[top] << " 入栈成功" << endl;
}
//遍历栈
void Stack::stack_show() {
if(stack_empty()) {
cout << "遍历失败" << endl;
}
for(int i=0; i<=top; i++) {
cout << data[i] << " ";
}
cout << endl;
}
//出栈
void Stack::stack_pop() {
if(stack_empty()) {
cout << "出栈失败" << endl;
}
//出栈,先弹后减
cout << data[top] << " 出栈成功" <<endl;
top--;
}
//销毁
void Stack::stack_delete() {
delete []data;
data=nullptr;
cout << "销毁成功" << endl;
}
3)main.cpp文件
#include <iostream>
#include <stack.h>
using namespace std;
int main()
{
Stack S1;
S1.stack_init();
//调用入栈函数
S1.stack_push(3);
S1.stack_push(8);
S1.stack_push(9);
S1.stack_push(6);
S1.stack_push(5);
//调用遍历函数
S1.stack_show();
//调用出栈函数
S1.stack_pop();
S1.stack_pop();
//调用遍历函数
S1.stack_show();
//调用销毁函数
S1.stack_delete();
//调用遍历函数
S1.stack_show();
return 0;
}
3、效果截图