最近在复习数据结构,涉及到堆栈的实现,通过类模板可以使堆栈的存储数据类型更为灵活,下面是堆栈的实现代码:
#ifndef MYSTACK_H
#define MYSTACK_H
#include <iostream>
using namespace std;
template <typename T>
class MyStack
{
public:
MyStack(int size);
~MyStack();
bool stackEmpty();//判空
bool stackFull();//判满
void clearStack();//清空
int stackLength();//长度
bool push(T elem);//压栈
bool pop(T &elem);//出栈
bool stackTop(T &elem);//返回栈顶
void stackTranverse();//遍历栈
private:
T *m_pStack;//栈指针
int m_iSize;//栈容量
int m_iTop;//栈顶
};
template <typename T>
MyStack<T>::MyStack(int size)
{
m_iSize = size;
m_pStack = new T[m_iSize];
m_iTop = 0;
}
template <typename T>
MyStack<T>::~MyStack()
{
delete m_pStack;
m_pStack = NULL;
}
template <typename T>
bool MyStack<T>::stackEmpty() {//判空
return m_iTop == 0 ? true : false;
}
template <typename T>
bool MyStack<T>::stackFull() {//判满
return m_iTop == m_iSize ? true : false;
}
template <typename T>
int MyStack<T>::stackLength() {//栈长度
return m_iTop;
}
template <typename T>
void MyStack<T>::clearStack() {//清空
m_iTop = 0;
}
template <typename T>
bool MyStack<T>::push(T elem) {//压栈
if (stackFull()) {
return false;
}
else {
m_pStack[m_iTop++] = elem;
return true;
}
}
template <typename T>
bool MyStack<T>::pop(T &elem) {//出栈
if (stackEmpty())
{
return false;
}
else {
elem = m_pStack[--m_iTop];
return true;
}
}
template <typename T>
bool MyStack<T>::stackTop(T &elem) {//返回栈顶元素
if (stackEmpty())
{
return false;
}
else {
elem = m_pStack[m_iTop-1];
return true;
}
}
template <typename T>
void MyStack<T>::stackTranverse() {//遍历栈
int i = 0;
for (i = 0; i < m_iTop; i++) {
cout << m_pStack[i];
}
}
#endif
其中需要注意的是类模板需要在每个函数之前写上模板定义template <typename T>,并且将类名写成MyStack<T>,函数中涉及到类的使用时用T代替即可。
接着我用一个坐标点类Coordinate来做测试:
在Coordinate类中利用函数重载运算符<<实现坐标点的打印
#include <ostream>
using namespace std;
class Coordinate
{
public:
friend ostream& operator<<(ostream &out, Coordinate &coor);
Coordinate(int x=0,int y=0)
{
m_iX = x;
m_iY = y;
}
~Coordinate()
{
}
private:
int m_iX;
int m_iY;
};
ostream& operator<<(ostream &out, Coordinate &coor) {
out << "(" << coor.m_iX << "," << coor.m_iX << ")" << endl;
return out;
}
下面是测试主函数:
#include <iostream>
#include "MyStack.h"
#include "Coordinate.h"
using namespace std;
int main() {
MyStack<Coordinate> *pStack = new MyStack<Coordinate>(5);
pStack->push(Coordinate(3, 5));//坐标点入栈
pStack->push(Coordinate(7, 5));
pStack->push(Coordinate(6, 5));
pStack->push(Coordinate(4, 5));
pStack->push(Coordinate(3, 5));
pStack->stackTranverse();//遍历栈
Coordinate t;
pStack->pop(t);//出栈
cout <<"弹出的t为:"<< t ;
cout << "长度:" << pStack->stackLength();
pStack->clearStack();//清空栈
pStack->stackTranverse();
//delete pStack;
//pStack = NULL;
system("pause");
return 0;
}
您可能感兴趣的文章:C++使用模板实现单链表C++利用链表模板类实现简易队列C++使用模板实现单链表(类外实现)