一、认识栈和队列
C++ Stacks(堆栈)
C++ Stack(堆栈)——是说实现了一个先进后出(FILO)的数据结构。
操作 比较和分配堆栈
empty() 堆栈为空则返回真
pop() 移除栈顶元素
push() 在栈顶增加元素
size() 返回栈中元素数目
top() 返回栈顶元素
C++ Queues(队列)
C++队列是一种容器适配器,它给予程序员一种先进先出(FIFO)的数据结构。
back() 返回最后一个元素
empty() 如果队列空则返回真
front() 返回第一个元素
pop() 删除第一个元素
push() 在末尾加入一个元素
size() 返回队列中元素的个数
二、
1.【基础题】–1.使用两个栈实现一个队列
解法:_s1为主栈;_s2为副站;副站是为主栈服务,一起完成队列的特性;
#include<iostream>
#include<stack>
using namespace std;
template<class T,class container=stack<T> >
class Queue
{
public:
T& Back()//返回队列最后一个元素的引用
{
if (!_s1.empty())//_s1不为空;
{
return _s1.top();
}
else//_s1为空,此时_s2为主栈
{
while (!_s2.empty())
{
_s1.push(_s2.top());
_s2.pop();
}
return _s1.top();
}
}
T& Front()//返回队列第一个元素的引用
{
if (!_s1.empty()&&_s2.empty())//_s1不为空,_s2为空
{
while (!_s1.empty())
{
_s2.push(_s1.top());
_s1.pop();
}
return _s2.top();
}
else//【_s1不为空,_s2不为空】/【_s1为空,_s2为空】/【_s1为空,_s2不为空】
{
return _s2.top();
}
}
void Pop()//删除队列第一元素
{
if (!_s1.empty()&&_s2.empty())//_s1不为空,_s2为空
{
while (!_s1.empty())
{
_s2.push(_s1.top());
_s1.pop();
}
_s2.pop();
}
else//【_s1不为空,_s2不为空】/【_s1为空,_s2为空】/【_s1为空,_s2不为空】
{
_s2.pop();
}
}
void Push(const T& x)//在队列末尾添加一个元素
{
_s1.push(x);
}
size_t Szie()const //返回队列的元素个数
{
return _s1.size()+_s2.size();
}
bool empty()const //判断对列是否为空,队列为空 返回真
{
return Szie()==0;
}
private:
stack<T> _s1;
stack<T> _s2;
};
int main()
{
Queue<int> q;
q.Push(1);//队列尾插
q.Push(2);
q.Push(3);
q.Push(4);
q.Push(5);
cout<<q.Front()<<endl;//1
cout<<q.Back()<<endl;//5
q.Pop();
cout<<q.Front()<<endl;//2
cout<<q.Back()<<endl;//5
q.Push(7);
q.Push(8);
cout<<q.Front()<<endl;//2
q.Pop();
cout<<q.Front()<<endl;//3
cout<<q.Szie()<<endl;//5
cout<<q.empty()<<endl;//0
}
2.【使用两个栈实现一个队列】
#include<iostream>
#include<queue>
using namespace std;
template <class T,class container=queue<T>>
class Stack
{
public:
void Push(const T& x)//在栈顶增加一个元素
{
if (!_q1.empty())
{
_q1.push(x);
}
else
{
_q2.push(x);
}
}
void Pop()//删除栈顶的元素
{
if (!_q1.empty())//_q1不为空
{
while(_q1.size()>1)
{
_q2.push(_q1.front());
_q1.pop();
}
_q1.pop();
}
else//_q1为空
{
while (_q2.size()>1)
{
_q1.push(_q2.front());
_q2.pop();
}
_q2.pop();
}
}
T& Top()//返回栈顶元素的引用
{
if (!_q1.empty())
{
return _q1.back();
}
else
{
return _q2.back();
}
}
size_t Size()const //返回栈的元素的个数
{
return _q1.size()+_q2.size();
}
bool Empty()const //判断栈是否为空
{
return Size()==0;
}
private:
queue<T> _q1;
queue<T> _q2;
};
int main()
{
Stack<int> s;
s.Push(1);
s.Push(2);
s.Push(3);
s.Push(4);
s.Push(5);
cout<<s.Top()<<endl;//5
s.Pop();
cout<<s.Top()<<endl;//4
s.Push(6);
s.Push(7);
cout<<s.Top()<<endl;//7
cout<<s.Size()<<endl;//6
cout<<s.Empty()<<endl;//0
return 0;
}