现在上传一份可以使用的栈的代码,方便童鞋们参考。
这个代码是将一个数组中的元素依次压入栈中,然后弹出。
可以使用这段代码来完成第二次作业。
P.S. 代码略丑,勿喷。
#include <iostream>
using namespace std;
#define MAXSIZE 100001
template<class type>
class SeqStack
{
private:
int top; // 栈顶指针
type* _stack; // 数组名
int maxsize; // 栈最大可容纳元素个数
public:
SeqStack();
SeqStack(int size);
virtual ~SeqStack()
{
delete []_stack;
}
void Push(const type &item);
type Pop();
type Top();
/*
* Empty()
* 判断栈是否为空
*/
int Empty() const
{
if ( -1 == top ){
return true;
}else {
return false;
}
}
/*
* Full()
* 判断栈是否满了
*/
int Full() const
{
if ( maxsize - 1 == top ){
return true;
} else {
return false;
}
}
/*
* Clear()
* 将栈里的元素清空
*/
void Clear()
{
top=-1;
}
};
/*
* SeqStack()
* 构造函数
*/
template <class type>
SeqStack<type>::SeqStack():
top(-1),maxsize(MAXSIZE)
{
_stack = new type[maxsize];
if ( _stack == NULL ){
cerr<<"allocate failed!"<<endl;
exit(1);
}
}
template <class type>
SeqStack<type>::SeqStack(int size):
top(-1),maxsize(size)
{
_stack = new type[maxsize];
if ( _stack == NULL ){
cerr<<"allocate failed!"<<endl;
exit(1);
}
}
/*
* Pop()
* 弹出栈顶元素
*/
template <class type>
type SeqStack<type>::Pop()
{
if ( Empty() ){
cerr<<"Empty!"<<endl;
exit(1);
}
type data = _stack[top];
top--;
return data;
}
/*
* Top()
* 返回栈顶元素
*/
template <class type>
type SeqStack<type>::Top()
{
if ( Empty() ){
cerr<<"Empty!"<<endl;
exit(1);
}
return _stack[top];
}
/*
* Push()
* 在栈中加入一个元素
*/
template <class type>
void SeqStack<type>::Push(const type &item )
{
if ( Full() ) {
cerr<<"Full!"<<endl;
exit(1);
}
_stack[++top] = item;
}
int main()
{
int num[10]={1,2,3,4,5,6,7,8,9,10};
SeqStack<int> stack(10);
for ( int i=0;i<10;i++){
//依次向栈中加入元素
stack.Push(num[i]);
}
while ( !stack.Empty() ){
//依次弹出栈顶的元素
cout<<stack.Pop()<<" ";
}cout<<endl;
getchar();getchar();
return 0;
}
--Carwest