平时编程里经常需要用到数据结构,比如 栈和队列 等, 为了避免每次用到都需要重新编写的麻烦现将 C++ 编写的 数据结构 栈 记录下来,以备后用。
将 数据结构 栈 用头文件的形式写成,方便调用。
#ifndef STACK_CLASS
#define STACK_CLASS #include<iostream>
#include<cstdlib>
using namespace std;
const int MaxStackSize=; //栈类的说明
template <class T>
class Stack
{
private:
T stacklist[MaxStackSize];
int top; public:
Stack(void); void Push(const T &item);
T Pop(void);
void ClearStack(void);
//访问栈顶元素
T Peek(void) const; int StackLength(void) const;
int StackEmpty(void) const;
int StackFull(void) const;
}; //默认构造函数
template <class T>
Stack<T>::Stack(void):top(-)
{} template <class T>
void Stack<T>::Push(const T &item)
{
if(top==MaxStackSize-)
{
cerr<<"Stack overflow!"<<endl;
exit();
}
top++;
stacklist[top]=item;
} template <class T>
T Stack<T>::Pop(void)
{
T temp;
if(top==-)
{
cerr<<"Attempt to pop an empty stack"<<endl;
exit();
}
temp=stacklist[top];
top--;
return temp;
} template <class T>
T Stack<T>::Peek(void) const
{
if(top==-)
{
cerr<<"Attempt to peek at an empty stack"<<endl;
exit();
}
return stacklist[top];
} template <class T>
int Stack<T>::StackLength(void) const
{
return top+;
} template <class T>
int Stack<T>::StackEmpty(void) const
{
return top==-;
} template <class T>
int Stack<T>::StackFull(void) const
{
return top==MaxStackSize-;
} template <class T>
void Stack<T>::ClearStack(void)
{
top=-;
}
#endif
具体的调用形式:
运行结果: