汉诺塔游戏流传已久,它主要存在着两种限制:1、先进后出;2、上小下大,而“先进后出”或者“LIFO”(后进先出,Last In First Out)就是汉诺塔移动的法则。
下面是用C++写的栈stack,经过一些简单测试可以实现栈的一些简单操作,测试环境为MS VS8。
- #include <tchar.h>
- /*
- 数据结构——栈
- 栈要遵守“后进先出的规则”
- */
- template <class ElemType>
- class stack{
- private:
- ElemType* stk_;
- int size_; //栈的大小
- int length_; //栈中元素的个数
- public:
- stack(int initsize);
- ~stack();
- void InitStack(int initsize); //初始化栈
- void DestroyStack(); //销毁栈
- int GetLength(); //取得栈中元素个数
- ElemType* GetTop(); //取得顶点元素
- bool StackEmpty(); //栈是否空
- bool StackFull(); //栈是否满
- bool push(ElemType* aItem); //添加元素,
- ElemType* pop(); //删除元素
- ElemType* Get(int index); //取得index位置的元素
- };
- template<class ElemType>
- void stack<ElemType>::InitStack(int initsize)
- {
- stk_ = new ElemType[initsize];
- size_ = initsize;
- length_ = 0;
- }
- template<class ElemType>
- void stack<ElemType>::DestroyStack()
- {
- delete[] stk_;
- length_ = 0;
- }
- template<class ElemType>
- stack<ElemType>::stack(int initsize)
- {
- InitStack(initsize);
- }
- template<class ElemType>
- stack<ElemType>::~stack()
- {
- DestroyStack();
- }
- template<class ElemType>
- int stack<ElemType>::GetLength()
- {
- return length_;
- }
- template<class ElemType>
- ElemType* stack<ElemType>::GetTop()
- {
- return &stk_[length_];
- }
- template<class ElemType>
- ElemType* stack<ElemType>::Get(int index)
- {
- if(index < length_)
- {
- return &stk_[index];
- }
- else return NULL;
- }
- template<class ElemType>
- bool stack<ElemType>::StackEmpty()
- {
- return(length_ == 0);
- }
- template<class ElemType>
- bool stack<ElemType>::StackFull()
- {
- return(length_ == size_);
- }
- template<class ElemType>
- bool stack<ElemType>::push(ElemType* aItem)
- {
- if(!StackFull())
- {
- stk_[length_] = *aItem;
- length_ ++;
- return true;
- }
- else return false;
- }
- template<class ElemType>
- ElemType* stack<ElemType>::pop()
- {
- ElemType* p = NULL;
- if(!StackEmpty())
- {
- length_ –;
- p = &stk_[length_];
- }
- return p;
- }
测试代码如下:
- stack<int>* stk = new stack<int>(10);
- for(int i = 0; i < 4; i++)
- {
- if (stk->push(&i))
- printf(“%d has been pushed./n”,i);
- else
- printf(“%d pushed failed!/n”,i);
- }
- printf(“%d has get top./n”,stk->GetTop());
- for(int i = 0; i < 4; i++)
- {
- printf(“%d has been getted./n”,*stk->Get(i));
- }
- for(int i = 0; i < 3; i++)
- {
- printf(“%d has been pop./n”,*stk->pop());
- }
- for(int i = 0; i < 4; i++)
- {
- int* a = stk->Get(i);
- if (a != NULL)
- printf(“%d has been getted./n”,*a);
- else
- printf(“No%d. Item is not exist!/n”,i);
- }
- delete stk;