c++类模板实现栈
// 栈.cpp: 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
using namespace std;
template<class Type>class Stack
{
public:
Stack(); //创建一个空栈
Stack(int size); //创建一个size大的栈
~Stack(); //回收一个栈
bool create(int size); //实际创建一个size大的栈
void destroy(); //销毁一个栈
bool isempty() const; //是否为空
bool isfull() const; //是否为满
bool pop(); //出栈
bool pop(Type &item); //出栈并返回出栈元素
bool push(Type &item); //进栈
bool gettop(Type &item); //取出栈顶元素
void display(); //显示栈中所有元素
private:
Type * stackspace; //栈空间具体实现
int top; //栈顶位置,为-1时栈为空
int stacksize; //栈大小,为0时栈未创建空间
};
template<class Type>
Stack<Type>::Stack()
{
stackspace = NULL;
stacksize = 0;
top = -1;
}
template<class Type>
Stack<Type>::Stack(int size)
{
stackspace = NULL;
stacksize = 0;
top = -1;
create(size);
}
template<class Type>
Stack<Type>::~Stack()
{
destroy();
}
template<class Type>
bool Stack<Type>::create(int size)
{
if (stacksize)
return false;
if (size < 0)
return false;
stackspace = new Type[size];
if (!stackspace)
return false;
stacksize = size;
top = -1;
return true;
}
template<class Type>
void Stack<Type>::destroy()
{
if (stackspace)
delete[] stackspace;
stackspace = NULL;
stacksize = 0;
top = -1;
}
template<class Type>
bool Stack<Type>::isempty() const
{
if (!stacksize)
return true;
return top == -1 ? true : false;
}
template<class Type>
bool Stack<Type>::isfull() const
{
if (!stacksize)
return true;
return top == stacksize-1 ?true:false;
}
template<class Type>
bool Stack<Type>::pop()
{
if (isempty())
return false;
top--;
return true;
}
template<class Type>
bool Stack<Type>::pop(Type & item)
{
if (isempty())
return false;
item = stackspace[top];
top--;
return true;
}
template<class Type>
bool Stack<Type>::push(Type & item)
{
if (!stacksize)
return false;
if (isfull())
return false;
top++;
stackspace[top] = item;
return true;
}
template<class Type>
bool Stack<Type>::gettop(Type & item)
{
if (isempty())
return false;
item = stackspace[top];
return true;
}
template<class Type>
void Stack<Type>::display()
{
if (isempty())
cout << "栈尚未建立!" << endl;
else
{
cout << "栈中元素由栈底到栈顶为:" << endl;
for (int i = 0; i <= top; i++)
cout << stackspace[i] << " ";
cout << endl;
}
}
int main()
{
Stack<char> s(10);
char a[4] = {'q','w','e'};
s.push(a[0]);
s.push(a[1]);
s.push(a[2]);
s.display();
s.pop();
char item;
s.pop(item);
cout << item << endl;
s.display();
system("pause");
return 0;
}