整体代码
#include <iostream>
#define MaxSize 5
using namespace std;
/*
栈是特殊的线性表,
只允许从一端输入,从另一端输出
*/
//栈的类定义
class SqStack
{
public:
int data[MaxSize]; //定义栈中元素
int top; //定义栈顶指针
};
//方法类定义
class Method
{
public:
void InitSqStack(SqStack& sqs); //初始化
void SqStackisEmpty(SqStack sqs); //判空
//打印栈,因为栈不能遍历,所以只能从栈顶依次打印其元素
void PrintSqStack(SqStack sqs);
void PushSqStack(SqStack& sqs); //入栈
int PopSqStack(SqStack& sqs); //出栈
};
void Method::InitSqStack(SqStack& sqs)
{
sqs.top = -1; //栈顶指针设为-1表示栈空
}
void Method::SqStackisEmpty(SqStack sqs)
{
if (sqs.top == -1)
cout << "栈为空" << endl;
else
cout << "栈不为空" << endl;
}
void Method::PrintSqStack(SqStack sqs)
{
while (sqs.top != -1)
{
cout << sqs.data[sqs.top--] << " ";
}
cout << endl;
}
void Method::PushSqStack(SqStack& sqs)
{
if (sqs.top == MaxSize - 1) //栈满
{
cout << "栈已经满了" << endl;
return;
}
int x;
//while (sqs.top != MaxSize - 1) {} 循环入栈
cin >> x;
sqs.data[++sqs.top] = x;
}
int Method::PopSqStack(SqStack& sqs)
{
if (sqs.top == -1)
{
cout << "栈已空" << endl;
return 0;
}
int p = sqs.data[sqs.top--];
return p; //用p返回出栈元素
}
int main()
{
SqStack sqs;
Method md;
md.InitSqStack(sqs);
md.SqStackisEmpty(sqs);
md.PushSqStack(sqs);
md.PrintSqStack(sqs);
md.PushSqStack(sqs);
md.PrintSqStack(sqs);
md.PushSqStack(sqs);
md.PrintSqStack(sqs);
md.SqStackisEmpty(sqs);
cout << md.PopSqStack(sqs) << endl;
return 0;
}
分块代码
栈的类定义
//栈的类定义
class SqStack
{
public:
int data[MaxSize]; //定义栈中元素
int top; //定义栈顶指针
};
方法类定义
//方法类定义
class Method
{
public:
void InitSqStack(SqStack& sqs); //初始化
void SqStackisEmpty(SqStack sqs); //判空
//打印栈,因为栈不能遍历,所以只能从栈顶依次出栈打印其元素
//因为没有传引用,所以尽管在打印的时候栈顶指针发生了变化,
//也并没有影响到后面的出栈操作
void PrintSqStack(SqStack sqs);
void PushSqStack(SqStack& sqs); //入栈
int PopSqStack(SqStack& sqs); //出栈
};
初始化
void Method::InitSqStack(SqStack& sqs)
{
sqs.top = -1; //栈顶指针设为-1表示栈空
}
判空
void Method::SqStackisEmpty(SqStack sqs)
{
if (sqs.top == -1)
cout << "栈为空" << endl;
else
cout << "栈不为空" << endl;
}
打印
void Method::PrintSqStack(SqStack sqs)
{
while (sqs.top != -1)
{
cout << sqs.data[sqs.top--] << " ";
}
cout << endl;
}
入栈
void Method::PushSqStack(SqStack& sqs)
{
if (sqs.top == MaxSize - 1) //栈满
{
cout << "栈已经满了" << endl;
return;
}
int x;
//while (sqs.top != MaxSize - 1) {} 循环入栈
cin >> x;
sqs.data[++sqs.top] = x;
}
出栈
int Method::PopSqStack(SqStack& sqs)
{
if (sqs.top == -1)
{
cout << "栈已空" << endl;
return 0;
}
int p = sqs.data[sqs.top--];
return p; //用p返回出栈元素
}
顺序栈就这么多东西了吧,如果有误,欢迎指正