The management of the stack can be used to chain list, of course, can also use fate group, compared to the list and array management more convenient, why??? Please open your eyes to see the bottom of the blog Master of the summary of the advantages of the array management stack: (1) Insert delete Convenient, array directly ++_top or--_top can, and linked list to delete the node null pointer, the trouble is dead; (2) High efficiency Ah, the array can be new T [_capacity] Easy, And the edge of the list side with new; (3) Actually, it's also involved in a CPU cache utilization
650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M00/7E/CE/wKiom1cI4LqCZK20AAHmHbMAcDQ477.png "title=" Capture 2. PNG "alt=" 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)
{}
Just start writing this function is silly than, hey, next time must remember
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;
}
}
Stack expansion function
void _checkcapacity ()
{
Cannot be opened with realloc because it does not invoke constructs and destructors
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<< " ";p op ();} cout<< "over" <<ENDL;;} Template<class t>void stack<t>::p ush (const t& x) { _ Checkcapacity (); _a[_top++]=x;} Template<class t>void stack<t>::p op () {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 >&NBSP;S2 (S1); stack<int> s3=S2; s1.print (); s2.print (); s3.print (); /* Cout<<s.top () <<endl;*/}int main () {teststack (); System ("pause"); return 0;}
650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M01/7E/CE/wKiom1cI4ZqSD8pXAAApOKSu7Tg759.png "title=" Capture 1. PNG "alt=" Wkiom1ci4zqsd8pxaaapoksu7tg759.png "/>
C + + template implementation stack