不使用库实现栈的基本操作

来源:互联网 发布:今日头条数据运营待遇 编辑:程序博客网 时间:2024/05/29 03:17
template<typenameT>
classStack
{
public:
                Stack()
                                :_a(NULL)
                                , _size(0)
                                , _capacity(0)
                {  }
                voidPush(constT&x)//相当于数组的尾插
                {
                                _CheckCapacity();
                                _a[_size++] =x;
                }
                voidPop()//移去栈顶元素,栈顶指向数组的最后一个数据
                {
                                if(_size != 0)
                                {
                                                _size--;
                                }
                }
                T& Top()//返回栈顶元素,即数组的最后一个元素
                {
                                return_a[_size-1];
                }
                boolEmpty() //如果栈为空,则返回true,否则,返回false
                {
                                if(_size == 0)
                                {
                                                returntrue;
                                }
                                else
                                {
                                                returnfalse;
                                }
                }
                size_tSize() //返回栈中元素数目
                {
                                return_size;
                }
                void_CheckCapacity()
                {
                                if(_size == _capacity)
                                {
                                         T* temp =newT[_capacity * 2 + 3];
                                   for(intindex = 0; index < _size; ++index)
                                                {
                                                                temp[index] = _a[index];
                                                }
                                                delete[] _a;
                                                _a = temp;
                                                _capacity = _capacity * 2 + 3;
                                }
                }
protected:
                T*   _a;
                size_t_size;
                size_t_capacity;
};

intmain()
{
                Stack<int> s;
                s.Push(3);
                s.Push(2);
                s.Push(1);
                //s.Pop();
                //s.Empty();
                intret=s.Top();
                cout << ret << endl;

                system("pause");
                return0;
}
0 0
原创粉丝点击