编写一个类,实现简单的栈。栈中有以下操作: 元素入栈、读栈顶元素,元素出栈,判断栈空,判断栈满。 栈的数据由大小为10的数组存放。 在主函数中测试栈的应用,完成如下操作: 将10、12、14依次入栈,读出栈顶元素,并打印。出栈,读出并打印栈顶元素。
stack.h
#include<iostream>
using namespace std;
class stack
{
private :
int
data
[
10
];
int
datacount;
//对应栈顶元素的下一个元素
public :
stack()
//构造函数,初始化。
{
for(
int
i
=
0;
i
<
10;
i
++)
data
[
i
]
=
0;
datacount
=
0;
}
void
push(
int
elem);
//入栈,插入元素
void
pop();
//出栈
int
gettop();
//获得栈顶元素
bool
isempty();
//判断栈是否为空
bool
isfull();
//判断栈是否为满
void
show_elem();
//遍历所有的栈内的元素
};
using namespace std;
class stack
{
private :
public :
};
stack.cpp
#include"stack.h"
bool stack :: isempty()
{
return
datacount
==
0;
//判断datacount==0这段语句是真是假
}
bool stack :: isfull()
{
return
datacount
==
10;
}
void stack :: push( int elem)
//压栈
{
if(
isfull())
return;
data
[
datacount
++
]
=
elem;
}
void stack :: pop()
{
if(
isempty())
return;
data
[
--
datacount
]
=
0;
}
int stack :: gettop()
{
if(
isempty())
return
-
1;
return
data
[
datacount
-
1
];
}
void stack :: show_elem()
{
if(
isempty())
return;
for(
int
i
=
0;
i
<
datacount;
i
++)
cout
<<
data
[
i
]
<<
" ";
cout
<<
endl;
}
bool stack :: isempty()
{
}
bool stack :: isfull()
{
}
void stack :: push( int elem)
{
}
void stack :: pop()
{
}
int stack :: gettop()
{
}
void stack :: show_elem()
{
}
main.cpp
#include"stack.h"
int main()
{
stack s;
s
.
push(
10);
s
.
push(
12);
s
.
push(
14);
cout
<<
"遍历整个栈的元素,由栈底到栈顶."
<<
endl;
s
.
show_elem();
cout
<<
"输出栈顶元素为:"
<<s
.
gettop()
<<
endl;
s
.
pop();
cout
<<
"剩余的元素为:";
s
.
show_elem();
}
int main()
{
}