/**************************
stack implement by C++
LAQ 2013.3.15
********************************/
#include <iostream>
#include <string>
using namespace std;
template<typename T> class MyStack
{
public:
MyStack():top(0),base(0),stacksize(0){}
bool InitStack();
bool ClearStack();
bool StackEmpty() const;
int StackLength() const;
T& GetTop()
{
if (top==base)
{
exit(1);
}
return *(top-1);
}
MyStack& Push(T &t)
{
if (top-base>=stacksize)
{
T *same_base=base;
T *same_top=top;
top=base=new T[INCREMENTSIZE+INITSTACKSiZE];
while (same_top!=same_base)
{
*top++=*same_base++;
}
//top=base+stacksize;
stacksize+=INCREMENTSIZE;
}
*top++=t;
return *this;
}
MyStack& Pop()
{
if (top==base)
{
exit(1);
}
--top;
return *this;
}
bool StackTraverse();
~MyStack()
{
DestoryStack();
}
private:
MyStack(const MyStack &); // declare but not defined:forbit to use copy constructor
bool DestoryStack();
T *top;
T *base;
int stacksize;
static int INITSTACKSiZE;
static int INCREMENTSIZE;
};
template<typename T> int MyStack<T>::INITSTACKSiZE=10;
template<typename T> int MyStack<T>::INCREMENTSIZE=10;
template<typename T> bool MyStack<T>::ClearStack()
{
// misss try catch excpetion hander
DestoryStack();
InitStack();
return true;
}
template<typename T> bool MyStack<T>::InitStack()
{
base=new T[INITSTACKSiZE];
if(!base)
exit(1);
top=base;
stacksize=INITSTACKSiZE;
return true;
}
template<typename T> bool MyStack<T>::StackEmpty() const
{
if (base==top)
{
return true;
}
return false;
}
template<typename T> bool MyStack<T>::DestoryStack()
{
delete[] base;
return true;
}
template<typename T> int MyStack<T>::StackLength() const
{
return top-base;
}
//template<typename T> MyStack& MyStack<T>::Push(T &t)
//template<typename T> MyStack& MyStack<T>::GetTop() const
//template<typename T> MyStack& MyStack<T>::Pop()
template<typename T> bool MyStack<T>::StackTraverse()
{
// CAUTION HERE
T *traver=base;
if (traver==0)
{
return false;
}
while (traver!=top)
{
cout<<*traver<<endl;
traver++;
}
return true;
}
int main(void)
{
// int a=2;
string a="123";
MyStack<string> ms;
ms.InitStack();
// 13
ms.Push(a);
ms.Push(a);
ms.Push(a);
ms.Push(a);
ms.Push(a);
ms.Push(a);
ms.Push(a);
ms.Push(a);
ms.Push(a);
ms.Push(a);
ms.Push(a);
ms.Push(a);
ms.Push(a);
ms.Pop();
ms.Pop();
ms.Pop();
// 10
ms.StackTraverse();
//ms.ClearStack();
return 0;
}
C++ 栈
最新推荐文章于 2024-08-15 05:02:54 发布