栈
头文件
#pragma once
#pragma once
#include<iostream>
using std::cout;
using std::endl;
template<class T>
class MyStack
{
public:
MyStack();
~MyStack();
void push(const T& data);
void travel()const;
T getTop()const;
void pop();
bool isEmpty()const;
private:
T* pArr;
size_t len;
size_t maxLen;
};
template<class T>
inline MyStack<T>::MyStack()
{
pArr = NULL;
len = maxLen = 0;
}
template<class T>
inline MyStack<T>::~MyStack()
{
if (pArr)
{
delete[] pArr;
}
pArr = NULL;
len = maxLen = 0;
}
template<class T>
inline void MyStack<T>::push(const T& data)
{
if (len >= maxLen)
{
maxLen = maxLen + (((maxLen >> 1) > 1) ? (maxLen / 2) : 1);
T* pNew = new T[maxLen];
if (NULL != pArr)
{
memcpy(pNew, pArr, sizeof(T) * len);
delete[] pArr;
}
pArr = pNew;
}
pArr[len++] = data;
}
template<class T>
inline void MyStack<T>::travel() const
{
cout << "__" << ":";
for (size_t i = 0; i < len; i++)
{
cout << pArr[i] << " ";
}
}
template<class T>
inline T MyStack<T>::getTop() const
{
return pArr[len - 1];
}
template<class T>
inline void MyStack<T>::pop()
{
if (len > 0)
{
len--;
}
}
template<class T>
inline bool MyStack<T>::isEmpty() const
{
return len==0;
}
源文件
#include<stdio.h>
#include"MyStack.h"
#include<iostream>
using namespace std;
class FenShu
{
public:
FenShu():fenzi(0),fenmu(0) {}
FenShu(int fz, int fm = 4)
{
fenzi = fz;
fenmu = fm;
}
friend ostream& operator<<(ostream& o, const
FenShu& fs);
private:
int fenzi;
int fenmu;
};
int main()
{
MyStack<int> vInt;
MyStack <FenShu> vFs;
for (int i = 0; i < 10; i++)
{
vInt.push(i);
vFs.push(FenShu(i));
}
while (!vInt.isEmpty())
{
cout << vInt.getTop() << " ";
vInt.pop();
}
while (!vFs.isEmpty())
{
cout << vFs.getTop() << " ";
vFs.pop();
}
return 0;
}
ostream& operator<<(ostream& o, const FenShu& fs)
{
return o << "(" << fs.fenzi << "/" << fs.fenmu << ")";
}