//MyStack1.h
#ifndef MYSTACK_H
#define MYSTACK_H
#include "Coordinate.h"
template <typename T>
class MyStack1
{
public:
MyStack1(int size);
~MyStack1();
bool stackEmpty();
bool stackFull();
void clearStack();
int stackLength();
bool push(T elem);
bool pop(T &elem);
void stackTraverse(bool isFromButtom);
private:
T *m_pBuffer;
int m_iSize;
int m_iTop;
};
#include "MyStack1.h"
#include <iostream>
using namespace std;
template <typename T>
MyStack1<T>::MyStack1(int size)
{
m_iSize = size;
m_pBuffer = new T[size];
m_iTop = 0;
}
template <typename T>
MyStack1<T>::~MyStack1()
{
delete []m_pBuffer;
}
template <typename T>
bool MyStack1<T>::stackEmpty()
{
if(0==m_iTop) //if(m_iTop == 0)
{
return true;
}
return false;
}
template <typename T>
bool MyStack1<T>::stackFull()
{
if(m_iTop == m_iSize) //>=
{
return true;
}
return false;
}
template <typename T>
void MyStack1<T>::clearStack()
{
m_iTop = 0;
}
template <typename T>
int MyStack1<T>::stackLength()
{
return m_iTop;
}
template <typename T>
bool MyStack1<T>::push(T elem)
{
if(stackFull())
{
return false;
}
m_pBuffer[m_iTop] = elem;
m_iTop++;
return true;
}
/*char MyStack::pop()
{
if(stackEmpty())
{
throw 1;
}
else
{
m_iTop--;
return m_pBuffer[m_iTop];
}
}*/
template <typename T>
bool MyStack1<T>::pop(T &elem)
{
if(stackEmpty())
{
return false;
}
m_iTop--;
elem = m_pBuffer[m_iTop];
return true;
}
template <typename T>
void MyStack1<T>::stackTraverse(bool isFromButtom)
{
if(isFromButtom){
for(int i = 0;i<m_iTop;i++)
{
cout<<m_pBuffer[i];
//m_pBuffer[i].printCoordinate();
}
}else{
for(int i= m_iTop-1;i>=0;i--)
{
cout<<m_pBuffer[i];
//m_pBuffer[i].printCoordinate();
}
}
}
#endif // MYSTACK_H
//Coordinate.h
#ifndef COORDINATE_H
#define COORDINATE_H
#include <iostream>
using namespace std;
class Coordinate
{
friend ostream &operator<<(ostream &out,Coordinate &coor);
public:
Coordinate(int x=0,int y=0);
void printCoordinate();
private:
int m_iX;
int m_iY;
};
#endif // COORDINATE_H
//Coordinate.cpp
#include "Coordinate.h"
#include <iostream>
using namespace std;
Coordinate::Coordinate(int x,int y)
{
m_iX = x;
m_iY = y;
}
void Coordinate::printCoordinate()
{
cout<<"("<<m_iX<<","<<m_iY<<")"<<endl;
}
ostream &operator<<(ostream &out,Coordinate &coor)
{
out<<"("<<coor.m_iX<<","<<coor.m_iY<<")"<<endl;
return out;
}
//main.cpp
#include <iostream>
#include "MyStack1.h"
#include "Coordinate.h"
using namespace std;
int main()
{
MyStack1<Coordinate> *pStack = new MyStack1<Coordinate>(5);
pStack->push(Coordinate(1,2));
pStack->push(Coordinate(2,3));
/*pStack->push('l');
pStack->push('l');
pStack->push('o');*/
pStack->stackTraverse(true);
pStack->stackTraverse(false);
cout<<pStack->stackLength()<<endl;
if(pStack->stackEmpty())
{
cout<<"栈为空"<<endl;
}
if(pStack->stackFull())
{
cout<<"栈为满"<<endl;
}
delete pStack;
pStack = NULL;
return 0;
}