栈的实现

##栈的实现 **
1、设置栈的最大值
const int maxsize = 100;
2、创建一个类来实现栈
**
class list
{
public:
list();
void push(int x);
void pop();
void gettop();
void empty();
void print();
private:
int data[maxsize];
int top;
};
**
3、填充类中的函数
**
list::list() //创建一个空栈
{
top = -1;
}
void list::gettop() //此函数是取栈顶元素
{
if (top != -1) //判断栈是否为空
{
cout << “栈顶元素为:” << data[top];
}
}
void list::push(int x) //像栈内插入元素
{
if (top == maxsize - 1)
{
throw"上溢";
}
top++;
data[top] = x;
cout << “第” << top + 1 << “个元素入栈成功!” << endl;
}
void list::pop() //取出栈内的元素
{
int x;
if (top == -1)
{
throw"下溢";
}
top–;
x = data[top];
cout << “出栈成功!” << "
***" << " 出栈的值为:" << x << endl;
}
void list::empty() //判断栈是否为空
{
if (top == -1)
{
cout << “栈为空!” << endl;
}
else
{
cout << “栈非空!” << endl;
}
}
void list::print()
{
if (top == -1)
{
cout << “栈为空!” << endl;
}
else
{
int i = 0;
cout << “栈内元素共有” << top + 1 << “个” << endl;
cout << “为:”;
for (int i = 0; i <= top; i++)
{
cout << data[i] << " ";
}
}
}
**
4、主函数的实现
**
int main()
{
int num, num1;
list mylist; //定义一个类变量
list(); //栈的初始化
cout << “请输入入栈元素个数:”;
cin >> num;
cout << “请输入入栈元素分别为:”;
for (int i = 0; i < num; i++)
{
int m;
cin >> m;
mylist.push(m); //调用list类里的函数
}
mylist.print();
cout << endl;
mylist.gettop();
cout << endl;
cout << “请输入出栈元素个数:”;
cin >> num1;
for (int i = 0; i < num1; i++)
{
mylist.pop();
}
cout << “出栈之后栈内元素为:” << endl;
mylist.print();
system(“pause”);
return 0;
}
**


include

using namespace std;
const int maxsize = 100;
class list
{
public:
list();
void push(int x);
void pop();
void gettop();
void empty();
void print();
private:
int data[maxsize];
int top;
};
list::list()
{
top = -1;
}
void list::gettop()
{
if (top != -1)
{
cout << “栈顶元素为:” << data[top];
}
}
void list::push(int x)
{
if (top == maxsize - 1)
{
throw"上溢";
}
top++;
data[top] = x;
cout << “第” << top + 1 << “个元素入栈成功!” << endl;
}
void list::pop()
{
int x;
if (top == -1)
{
throw"下溢";
}
top–;
x = data[top];
cout << “出栈成功!” << “*****” << " 出栈的值为:" << x << endl;
}
void list::empty()
{
if (top == -1)
{
cout << “栈为空!” << endl;
}
else
{
cout << “栈非空!” << endl;
}
}
void list::print()
{
if (top == -1)
{
cout << “栈为空!” << endl;
}
else
{
int i = 0;
cout << “栈内元素共有” << top + 1 << “个” << endl;
cout << “为:”;
for (int i = 0; i <= top; i++)
{
cout << data[i] << " ";
}
}
}
int main()
{
int num, num1;
list mylist;
list();
cout << “请输入入栈元素个数:”;
cin >> num;
cout << “请输入入栈元素分别为:”;
for (int i = 0; i < num; i++)
{
int m;
cin >> m;
mylist.push(m);
}
mylist.print();
cout << endl;
mylist.gettop();
cout << endl;
cout << “请输入出栈元素个数:”;
cin >> num1;
for (int i = 0; i < num1; i++)
{
mylist.pop();
}
cout << “出栈之后栈内元素为:” << endl;
mylist.print();
system(“pause”);
return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值