1.栈
定义:栈是只允许末端进行插入和删除的线性表,具有先进后出或先进后出的特性
栈用数组实现较好,因为它只在尾上进行操作,进行增删比较方便。
1.栈
<span style="font-family:Microsoft YaHei;font-size:18px;">#pragma once
//栈具有后进先出的原则,
template<class T>
class Stack
{
public:
//构造函数
Stack()
:_a(NULL)
, _top(0)
, _capcity(0)
{}
//析构函数
~Stack()
{
Clear();
}
//push
void PushBack(const T& x)
{
//1.先检查容量 2.向数据中插入新数据 3.++_top
CheckCapcity();
_a[_top++] = x;
}
//pop
void PopBack()
{
if (_top == 0)
{
cout << "NULL" << endl;;
return; //记得加这句,不然停不下来,越界访问,有bug
}
else
--_top;
}
//size
int Size()
{
return _top;
}
//empty
bool Empty()
{
return _top == 0;
}
//top
T& Top()
{
return _a[_top-1];
}
void Print()
{
for (int i = 0; i < _top; i++)
{
cout << _a[i] << " ";
}
cout << endl;
}
protected:
void CheckCapcity()
{
if (_top == _capcity)
{//扩充的是_capcity,所以只改变_capcity,其他的不用动
_capcity = _capcity * 2 + 3;
T* tmp = new T[_capcity]; //重新开辟空间
for (int i = 0; i < _top; i++)
{
tmp[i] = _a[i]; //将数据都拷贝到新空间中
}
delete[] _a; //释放原空间,
_a = tmp; //然后指针重新指向新空间
}
}
void Clear()
{
if (_a!=NULL)
{
delete[] _a;
_top = 0;
_capcity = 0;
}
}
protected:
T* _a; //栈底层封装数组,利用数组实现栈,这样做就可以限制只在尾上做处理
size_t _top;//指向最上面的元素,相当关于以前数组的的size
size_t _capcity;//当前栈的总容量
};</span>
测试用例:
<span style="font-family:Microsoft YaHei;font-size:18px;">#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
#include"Stack.h"
//Test Push
void Test1()
{
Stack<int> s1;
s1.Push(1);
s1.Push(2);
s1.Push(3);
s1.Push(4);
s1.Push(5);
while (!s1.Empty())
{
cout << s1.Top() << endl;
s1.Pop();
}
}
//Test Pop
void Test2()
{
Stack<int> s1;
s1.Push(1);
s1.Push(2);
s1.Push(3);
s1.Push(4);
s1.Push(5);
s1.Pop();
s1.Pop();
s1.Pop();
s1.Pop();
s1.Pop();
s1.Pop();
s1.Pop();
while (!s1.Empty())
{
cout << s1.Top() << endl;
s1.Pop();
}
}
//Test size()
void Test3()
{
Stack<int> s1;
s1.Push(1);
cout << s1.size() << endl;
s1.Push(2);
cout << s1.size() << endl;
s1.Push(3);
cout << s1.size() << endl;
s1.Push(4);
cout << s1.size() << endl;
s1.Push(5);
cout << s1.size() << endl;
}
//test empty
void Test4()
{
Stack<int> s1;
s1.Push(1);
s1.Push(2);
s1.Pop();
s1.Pop();
cout << s1.Empty() << endl;
}
//test
void Test5()
{
Stack<int> s1;
s1.Push(1);
cout<<s1.Top()<<endl;
s1.Push(2);
cout << s1.Top() << endl;
s1.Push(3);
cout << s1.Top() << endl;
s1.Push(4);
cout << s1.Top() << endl;
s1.Push(5);
cout << s1.Top() << endl;
}
int main()
{
//Test1();
//Test2();
//Test3();
//Test4();
Test5();
system("pause");
return 0;
}
</span>
如有不正确的地方,希望能够指出,一起学习,谢谢了。