摘要:用C++模板实现一个原始栈的操作,包括插入,删除,判空,清空,取栈顶元素,取栈长度
关键字:C++ ,stack
使用C++模板类实现了一个原始栈,功能有:清空栈,判空,取栈顶元素,插入,删除,取栈长度,支持基本的数据类型和自定义的数据类型,但是没有做异常处理。
代码如下
/*!
* \file stack.cpp
* \date 2017/04/13 8:40
*
* \author 甘超浩
* Contact: chht123@126.com
*
* \brief 使用模板来实现一个简单栈,支持基本数据类型和自定义数据类型
*
* TODO: 异常捕捉
*
* \note
*/
#include <iostream>
#include <string>
#define MAX_STACKSIZE 50
using namespace std;
template<class T>
struct stack
{
T data[MAX_STACKSIZE];
int top = -1;
void ClearStack();
bool StackEmpty();
int GetTop(T & e);
void Push(T e);
T Pop();
int StackLength();
};
template<class T>
void stack<T>::ClearStack()
{
this->top = -1;
}
template<class T>
bool stack<T>::StackEmpty()
{
return this->top == -1 ? true : false;
}
template<class T>
int stack<T>::GetTop(T & e)
{
if(this->StackEmpty())
{
return 0;
}
e = this->data[s.top];
return 1;
}
template<class T>
void stack<T>::Push(T e)
{
if(this->StackLength() >= MAX_STACKSIZE)
{
return;
}
this->top++;
this->data[this->top] = e;
}
template<class T>
T stack<T>::Pop()
{
if(this->StackEmpty())
{
return (T)0;
}
T e = this->data[this->top];
this->top--;
return e;
}
template<class T>
int stack<T>::StackLength()
{
return this->top + 1;
}
void test_stack(void)
{
stack<char> s;
string str = s.StackEmpty() ? "是" : "否";
cout << "s是否为空:" << str << endl;
s.Push('a');
s.Push('b');
cout << "栈顶元素:" << s.Pop() << endl;
cout << "栈顶元素:" << s.Pop() << endl;
cout << "s的大小:" << s.StackLength() << endl;
}
结果截图如下: