栈(Stack)
栈(Stack): 是只允许在末端(栈顶)进行插入和删除的线性表。
性质:
具有先进后出(FILO),后进先出(LIFO,Last In First Out)的性质.
两种实现方式:
一种是顺序存储,和数组类似。
一种是链式存储,和单链表类似。
栈的应用:
- 算术表达式求值。波兰表达式(后缀表达式)
- 迷宫问题
- 栈模拟压栈,实现递归转为非递归
主要实现的接口:
void Push(const T& x);// 从栈顶插入一个数据
void Pop();// 从栈顶删除一个数据
Size_t size();// 栈中元素的总个数
T& Top();// 栈顶元素
void Print();//从栈顶开始打印栈中的元素值
下面通过顺序存储来实现栈(Stack):
#pragma once
#include<iostream>
using namespace std;
template < class T>
class Stack
{
public:
Stack()
:_a(NULL)
,_size(0)
,_capacity(0)
{}
~Stack()
{
if( !empty() )
{
delete[] _a;
}
}
bool empty()
{
return _size == 0;
}
void CheckCapacity()
{
if( _size >= _capacity )
{
_capacity = _capacity > 0 ? _capacity*2 : 2;
T* tmp = new T[_capacity];
for(size_t i = 0; i <_size ; ++i)
{
tmp[i] = _a[i];
}
delete[] _a;
_a = tmp;
}
}
void Push(const T& x)
{
CheckCapacity();
_a[_size] = x;
++_size;
}
void Pop()
{
if( !empty() )
{
--_size;
}
}
T& Top()
{
if( !empty() )
{
return _a[_size-1];
}
}
size_t Size()
{
return _size;
}
void Print()//从栈顶开始打印元素
{
for( size_t i = _size; i > 0 ; --i )
{
cout<<_a[i-1]<<" ";
}
cout<<endl;
}
protected:
T* _a;
size_t _size;
size_t _capacity;
};
void test()
{
Stack<int> s;
s.Push(1);
s.Push(2);
s.Push(3);
s.Print();
s.Pop();
s.Print();
//while( !s.empty() )//从栈顶打印数据
//{
// cout<<s.Top()<<" ";
// s.Pop();
//}
//cout<<endl;
cout<<s.Top()<<endl;
cout<<s.Size()<<endl;
}
队列(Queue)
队列的定义:
队列值允许在表的队尾进行插入,队头进行删除。
队列的性质:
先进先出(FIFO,First In First Out)
队列的应用:
- 生产者和消费者模型
- 任务队列
- 图的广度优先遍历
代码实现:
#pragma once
#include <iostream>
using namespace std;
template <class T>
struct QueueNode
{
T _data;
QueueNode<T>* next;
//构造函数
QueueNode( const T& x )
:_data(x)
,next(NULL)
{}
};
template <class T>
class Queue
{
typedef QueueNode<T> Node;
public:
Queue()
:_head(NULL)
,_tail(NULL)
{}
bool empty()
{
return _head == NULL;
}
void Push( const T& x )
{
//if( _head == NULL )
if( empty() )
{
_head = _tail = new Node(x);
}
else
{
_tail->next = new Node(x);
_tail = _tail->next;
}
}
void Pop()
{
if( _head == NULL )
{
return;
}
else if( _head == _tail )
{
delete _head;
_head = _tail = NULL;
}
else
{
Node* tmp = _head;
_head = _head->next ;
delete tmp;
}
}
size_t Size()
{
Node* cur = _head;
size_t size = 0;
while(cur)
{
cur = cur->next ;
++size;
}
return size;
}
T& Front()
{
return _head->_data;
}
void Print()
{
Node* cur = _head;
while(cur)
{
cout<<cur->_data<<" ";
cur = cur->next;
}
cout<<endl;
}
protected:
Node* _head;
Node* _tail;
};
void test()
{
Queue<int> q;
q.Push(1);
q.Push(2);
q.Push(3);
q.Push(4);
q.Push(5);
q.Print();
q.Pop();
q.Print();
cout<<q.Front()<<endl;
cout<<q.Size()<<endl;
/*while( !q.empty() ) //从头到尾打印队列
{
cout<<q.Front()<<" ";
q.Pop();
}
cout<<endl;*/
}