栈的实现
栈的特点:先进后出
#include <iostream>
using namespace std;
const int MAX = 6;//设置栈的长度为6
class STACK
{
private:
int data[MAX];
int top;
public:
STACK(void){
top = 0;
cout << "栈已被初始化!" << endl;
}
~STACK(void){
cout << "栈已被销毁!" << endl;
}
bool isEmpty(void);//判断栈是否为空
void push(int a);//进栈
int pop(void);//出栈
};
bool STACK::isEmpty(void) {
return top == 0 ? true : false;
}
void STACK::push(int a) {
if (top == MAX) {//栈若是满了,返回
cout << "栈已经满了!" << endl;
return;
}
//未满,存入数组
data[top] = a;
top++;
}
int STACK::pop(void)
{
if (top == 0) {//栈若为空,返回
cout << "栈是空的!" << endl;
return 0;
}
//非空,弹出栈顶数组
top--;
return data[top];
}
int main()
{
STACK s1, s2;
for (int i = 0;i < MAX;i++)
{
s1.push(i);
}
for (int i = 0;i < MAX;i++)//往s1栈中压入数据
{
cout<<s1.pop()<<" ";
}
for (int i = 0;i < MAX;i++)//从s1栈中弹出数据
{
s1.push(2 * i);
}
for (int i = 0;i < MAX;i++)//将s1栈中的数值乘以2,压入s2栈中
{
s2.push(s1.pop());
}
cout << endl;
do {//从s2栈中弹出数据
cout << s2.pop() << " ";
} while (!s2.isEmpty());
cout << endl;
system("pause");
return 0;
}
转载自:黑凤梨の博客