@TOC
1. 手动实现顺序栈,要求实现数据结构中,所有栈的相关操作
#include <iostream>
using namespace std;
// 1.top()访问栈顶元素
// 2.push()将元素压入栈顶
// 3.pop()移除栈顶元素,若想访问栈下的元素,必须先移除栈顶
// 4.empty()用来检测栈是否为空,若是空,返回的是true,不是空返回false
// 5.size()用来返回栈中元素的个数
#define MAX_SIZE 10 // 栈的最大容量
class zhan // 栈的类
{
private:
int height; // 当前栈的高度
int stack[MAX_SIZE]; // 栈
public:
zhan() : height(-1) // 无参构造
{
cout << "无参构造函数" << endl;
}
// stack() {} // 有参构造函数
// ~stack() {}
public:
bool top(int &num); // 访问栈顶元素
bool push(int a); // 入栈
bool pop(); // 出栈
bool empty(); // 判空
int size(); // 返回栈中元素个数
};
bool zhan::top(int &num) // 访问栈顶元素
{
// 判空
if (empty() == true)
{
cout << "访问栈顶失败,栈为空" << endl;
return false;
}
num = stack[height];
return true;
}
bool zhan::push(int a) // 入栈
{
if (height == (MAX_SIZE - 1)) // 判满
{
cout << "入栈失败,栈已满" << endl;
return false;
}
height++;
stack[height] = a;
cout << "入栈成功"
<< "入栈位置: " << height << "入栈元素为: " << a << endl;
return true;
}
bool zhan::pop() // 出栈
{
if (empty() == true)
{
cout << "出栈失败,栈为空" << endl;
return false;
}
height--;
cout << "出栈 height= " << height << endl;
return true;
}
bool zhan::empty() // 判空
{
if (height == 0)
return true;
return false;
}
int zhan::size() // 返回栈中元素个数
{
return height + 1;
}
int main(int argc, char *argv[])
{
zhan a;
a.push(33); // 入栈
a.push(44); // 入栈
a.push(55); // 入栈
cout << "栈的高度为: " << a.size() << endl; // 返回栈中元素个数
a.pop(); // 出栈
int num;
a.top(num);
cout << "栈顶元素为: " << num << endl; // 栈顶元素
system("pause");
return 0;
}