MyStack.h
#ifndef MYSTACK_H
#define MYSTACK_H
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); //元素出栈,栈顶下降
void stackTraverse(bool isFromButton); //遍历所有元素
private:
T *m_pBuffer; //栈空间指针
int m_iSize; //栈容量
int m_iTop; //栈顶
};
template<typename T>
MyStack<T>::MyStack(int size)
{
m_iSize = size;
m_pBuffer = new T[m_iSize]; //申请类型T大小为m_iSize的内存
m_iTop = 0;
}
template<typename T>
MyStack<T>::~MyStack()
{
delete[]m_pBuffer; //释放内存
m_pBuffer = NULL;
}
template<typename T>
bool MyStack<T>::stackEmpty()
{
if (0 == m_iTop)
return true;
else
return false;
}
template<typename T>
bool MyStack<T>::stackFull()
{
if (m_iSize <= m_iTop)
return true;
else
return false;
}
template<typename T>
void MyStack<T>::clearStack()
{
m_iTop = 0;
}
template<typename T>
int MyStack<T>::stackLength()
{
return m_iTop;
}
template<typename T>
bool MyStack<T>::push(T elem)
{
if (stackFull()) //入栈先判满
return false;
m_pBuffer[m_iTop] = elem;
m_iTop++;
return true;
}
template<typename T>
bool MyStack<T>::pop(T &elem)
{
if (stackEmpty()) //出栈判空
return false;
m_iTop--;
elem = m_pBuffer[m_iTop];
return true;
}
template<typename T>
void MyStack<T>::stackTraverse(bool isFromButton)
{
if (isFromButton)
{
//从底到顶索引
for (int i = 0; i<m_iTop; i++)
{
cout << m_pBuffer[i]; //基本类型没问题
}
}
else
{
//从顶到低遍历
for (int i = m_iTop - 1; i >= 0; i--)
{
cout << m_pBuffer[i];
}
}
}
#endif
coordinate.h
#ifndef COORDINATE_H
#define COORDINATE_H
#include<ostream>
using namespace std;
class Coordinate
{
friend ostream &operator<<(ostream &out,Coordinate &coor);
public:
Coordinate(int x=0 ,int y=0);
void printCoordinate();
private:
int x;
int y;
};
#endif
coordinate.cpp
#include"coordinate.h"
#include<iostream>
using namespace std;
Coordinate::Coordinate(int _x,int _y)
{
x = _x;
y = _y;
}
void Coordinate::printCoordinate()
{
cout << "(" << x << "," << y << ")"<< endl;
}
//运算符重载
ostream &operator<<(ostream &out, Coordinate &coor)
{
cout << "(" << coor.x << "," << coor.y << ")" << endl;
return out;
}
main.cpp
#include<iostream>
#include"stdlib.h"
#include"MyStack.h"
#include"coordinate.h"
using namespace std;
int main()
{
MyStack<Coordinate> *pStack = new MyStack<Coordinate>(5);
pStack->push(Coordinate(2, 3));
pStack->push(Coordinate(4, 7));
pStack->push(Coordinate(6, 9));
pStack->stackTraverse(true);
return 0;
}