栈的管理可以用运链表,当然啦也可以用运数组,相比链表而数组管理起来更加方便,为什么呢???请睁大眼睛看下边博主大人的总结
数组管理栈的优点:
(1)插入删除方便,数组直接将++_top或者--_top即可,而链表还要删除节点置空指针,麻烦死啦;
(2)效率高呀,数组一次能够new T [_capacity]省事,而链表边用边new;
(3)其实这里还牵扯到一个cpu的高速缓存利用率

wKiom1cI4LqCZK20AAHmHbMAcDQ477.png

static and queue.h

#pragma  once

#include<iostream>

using namespace std;

template<class T>

class stack

{

public:


    stack()

:_a(0)

,_top(0)

,_capacity(0)

{}

   //刚开始写这个函数的时候很傻比,哎,下次一定铭记

stack(const stack <T>& s)

:_a(new T[s._capacity])

    ,_top(s._top)

,_capacity(s._capacity)

{

int i=0;

for(i=0;i<s._top;i++)

{

_a[i]=s._a[i];

}


}

stack<T>& operator=(const stack<T>& s)

{

if(this!=&s)

{

delete [] _a;

_a=new T [s._capacity*sizeof(T)];

int i=0;

for(i=0;i<_top;i++)

{

a[i]=s._a[i];

}

_top=s._top;

_capacity=s._capacity;


}

return *this;

}

~stack()

{

if(_a!=NULL)

{

delete [] _a;

_a=NULL;

}

}

//栈扩容函数

void _checkcapacity()

{

//不能用realloc开辟因为它不会调用构造和析构函数

              if(_top==_capacity)

{

_capacity=_capacity*2+3;

               

T* tmp=new T [_capacity];

int i=0;

for(i=0;i<_top;i++)

{

tmp[i]=_a[i];

}

delete [] _a;

_a=tmp;

}

}

void push(const T& x);

void pop();

T& top();

bool empty();

size_t size();

void print();

protected:

T * _a;

size_t _top;

size_t _capacity;

};

static and queue.cpp
#define _CRT_SECURE_NO_WARNINGS 1
#include"stack and queue.h"
#include<assert.h>
using namespace std;

template<class T>
void stack<T>::print()
{
	while(!empty())
	{
	cout<<_top<<" ";
	pop();
	}
	cout<<"over"<<endl;;
}

template<class T>
void stack<T>::push(const T& x)
{
   _checkcapacity();
   _a[_top++]=x;
}

template<class T>
void stack<T>::pop()
{
	if(_top>0)
	{
		--_top;
	}
}
template<class T>
T& stack<T>::top()
{
	if(!empty())
	{
	return _a[_top-1];
	}
}

template<class T>
bool stack<T>::empty()
{
	return (_top==0);
}


void TestStack()
{
   stack<int> s1;
   
   s1.push(1);
   s1.push(2);
   s1.push(3);
   s1.push(4);
 stack<int> s2(s1);
 stack<int> s3=s2;
   s1.print();
   s2.print();
   s3.print();
   /*cout<<s.top()<<endl;*/
}
int main()
{
	TestStack();
	system("pause");
	return 0;
}

wKiom1cI4ZqSD8pXAAApOKSu7Tg759.png