一、栈:
特点:后进先出(LIFO),只允许在末端进行插入和删除,所以适用于用数组(即一段连续的空间)来实现,经常性在数组尾部插入删除
代码实现:
#include <iostream>
#include <cstdlib>
#include <assert.h>
using namespace std;
template <typename T>
class Stack
{
public:
Stack()
:_a(NULL)
,_size(0)
,_capacity(0)
{}
Stack(const Stack<T> &s)
:_a(new T[s._capacity])
,_size(s._size)
,_capacity(s._capacity)
{
for(size_t i=0;i<_size;++i)
{
_a[i]=s._a[i];
}
}
Stack<T>& operator=(const Stack<T> &s)
{
if(this!=&s)
{
T *temp=new T[s._capacity];
for(size_t i=0;i<s._size;++i)
{
temp[i]=s._a[i];
}
delete[] _a;
_a=temp;
_size=s._size;
_capacity=s._capacity;
}
return *this;
}
~Stack()
{
if(_a!=NULL)
{
delete[] _a;
_a=NULL;
_size=0;
_capacity=0;
}
}
void Push(const T &data)
{
CheakCapacity();
_a[_size++]=data;
}
void Pop()
{
assert(_size);
--_size;
}
T& Top()
{
assert(_size);
return _a[_size-1];
}
const T& Top()const
{
assert(_size);
return _a[_size-1];
}
size_t Size()
{
return _size;
}
bool Empty()
{
return _size==0;
}
private:
void CheakCapacity()
{
if(_size>=_capacity)
{
T *temp=new T[_capacity*2+3];
for(int i=0;i<_size;++i)
{
temp[i]=_a[i];
}
delete[] _a;
_a=temp;
_capacity=_capacity*2+3;
}
}
private:
T* _a;
size_t _size; //统计栈内元素个数
size_t _capacity;//统计栈的容量大小
};
void Test1()
{
Stack<int> s1;
s1.Push(1);
Stack<int> s2(s1);
Stack<int> s3;
s3=s1;
s1.Push(2);
s1.Push(3);
s1.Push(4);
cout<<s1.Size()<<endl;
while(!s1.Empty()) //判空循环,每次输出栈顶元素,并且依次删除
{
cout<<s1.Top()<<" ";
s1.Pop();
}
cout<<endl;
}
int main()
{
Test1();
system("pause");
return 0;
}
测试结果:
1.栈中拷贝构造函数与赋值运算符重载监视测试结果
2.栈中其它函数测试结果
二、队列:
特点:先进先出(FIFO),在队尾进行插入,在队头进行删除,所以适用于用链表实现
代码实现:(头文件与栈实现的头文件相同)
template <typename T>
struct QueueNode
{
T _data;
QueueNode<T> *_next;
QueueNode(const T &x)
:_data(x)
,_next(NULL)
{}
};
template <typename T>
class Queue
{
typedef QueueNode<T> Node;
public:
Queue()
:_head(NULL)
,_tail(NULL)
{}
~Queue()
{
while(_head)
{
Node *del=_head;
_head=_head->_next;
delete del;
}
_head=_tail=NULL;
}
void Push(const T &q)
{
Node *newNode=new Node(q);
if(_head==NULL) //若为空
{
_head=newNode;
_tail=_head;
}
else
{
_tail->_next=newNode;
_tail=_tail->_next;
}
}
void Pop()
{
assert(_head);
if(_head==_tail) //若为空或只有一个结点
{
delete _head;
_head=_tail=NULL;
}
else
{
Node *del=_head;
_head=_head->_next;
delete del;
del=NULL;
}
}
T& Front()
{
assert(_head);
return _head->_data;
}
const T& Front()const
{
assert(_head);
return _head->_data;
}
T& Back()
{
assert(_head);
return _tail->_data;
}
const T& Back()const
{
assert(_head);
return _tail->_data;
}
bool Empty()
{
return _head==NULL;
}
size_t Size()
{
assert(_head);
Node *cur=_head;
size_t count=0;
while(cur)
{
count++;
cur=cur->_next;
}
return count;
}
private:
Node *_head;
Node *_tail;
};
void Test2()
{
Queue<int> q1;
q1.Push(1);
q1.Push(2);
q1.Push(3);
q1.Push(4);
cout<<q1.Size()<<endl;
cout<<q1.Back()<<endl;
while(!q1.Empty())
{
cout<<q1.Front()<<" ";
q1.Pop();
}
cout<<endl;
}
int main()
{
Test2();
system("pause");
return 0;
}
测试结果: