**模拟实现栈**
#include<iostream>
#include<windows.h>
#include<stack>
using namespace std;
template<class T>
class Stack
{
public:
Stack(size_t capacity = 5)
{
_capacity = capacity+3;//防止传NULL
_pData = new T[_capacity];
_size = 0;
}
Stack(const Stack<T>& s)
{
T *Ptemp = new T[s._capacity];
for (size_t i = 0; i < s._size; ++i)
{
Ptemp[i] = s._pData[i];
}
delete[]_pData;
_pData = Ptemp;
_capacity = s._capacity;
_size = s._size;
}
Stack<T>& operator=(const Stack<T>& s)
{
//检查自我赋值
if (this == &s)
return *this;
//释放原有资源
delete[]_pData;
//分配新的内存资源,并复制内容
T *pTemp = new T[s._capacity];
for (size_t i = 0; i < s._size; ++i)
{
pTemp[i] = s._pData[i];
}
_pData = pTemp;
_capacity = s._capacity;
_size = s._size;
//返回本对象的引用
return *this;
}
void Push(const T& x)
{
_CheckCapacity();
_pData[_size++]=x;
}
void Pop()
{
if (!Empty())
{
_pData[_size--];
}
}
size_t Size()const
{
return _size;
}
T Top()
{
return _pData[_size-1];
}
const T& Top()const
{
return _pData[_size-1];
}
bool Empty()const
{
if (0 == _size)
return true;
return false;
}
void Print()
{
for (size_t i = 0; i<_size; ++i)
{
//cout << *(_pData++) << endl;//错误操作
cout << *(_pData + i) << " " ;
}
cout << endl;
}
private:
void _CheckCapacity()
{
if (_size >= _capacity)
{
// 申请空间
T* pTemp = new T[_capacity*2 + 3];
// 拷贝元素
//memcpy(); 缺点:浅拷贝 有点:速度快
for (size_t i = 0; i < _size; i++)
{
pTemp[i] = _pData[i];
}
// 释放旧空间
delete[]_pData;
// 指向新空间
_pData = pTemp;
_capacity *= 2;
}
}
private:
T* _pData;
size_t _capacity;
size_t _size;
};
int main()
{
Stack<int>s;
s.Push(1);
s.Push(2);
s.Push(3);
s.Push(4);
s.Push(5);
Stack<int>s1(s);
cout << "************* Stack<int>s1(s) ***************" << endl;
s1.Print();
cout << "s1.Size()" << " " << s1.Size() << endl;
cout << "s1.Top()" << " " << s1.Top() << endl;
cout << "s1.Empty()" << " " << s1.Empty() << endl;
cout << "************* Pop()两个元素之后 *************" << endl;
s1.Pop();
s1.Pop();
s1.Print();
cout << "s1.Size()" << " " << s1.Size() << endl;
cout << "s1.Top()" << " " << s1.Top() << endl;
cout << "s1.Empty()" << " " << s1.Empty() << endl;
cout << "************* Stack<int>s2; s2 = s ************" << endl;
Stack<int>s2;
s2 = s;
s2.Print();
cout << "s2.Size()" << " " << s2.Size() << endl;
cout << "s2.Top()" << " " << s2.Top() << endl;
cout << "s2.Empty()" << " " << s2.Empty() << endl;
cout << "************** Pop()三个元素之后 ************" << endl;
s2.Pop();
s2.Pop();
s2.Pop();
s2.Print();
cout << "s2.Size()" << " " << s2.Size() << endl;
cout << "s2.Top()" << " " << s2.Top() << endl;
cout << "s2.Empty()" << " " << s2.Empty() << endl;
system("pause");
return 0;
}
模拟实现栈
最新推荐文章于 2022-10-12 20:28:49 发布