分析
- 棧:后進先出
- 隊列:先進先出
要使用兩個棧實現隊列(先進先出),主要思路是
1.插入一個元素:直接將元素插入stack1即可。
2.刪除一個元素:當stack2不為空時 ,直接彈出棧頂元素,當stack2為空時,將stack1元素逐個彈出並壓入stack2,然后再彈出棧頂元素。
具體看下面的代碼。
代碼實現
#include <iostream>
#include <stack>
using namespace std;
template<class T>
class Queue
{
private:
stack<T> s1;
stack<T> s2;
public:
//入隊
void Push(const T &val);
//出隊
void Pop();
//返回隊首元素
T& Front();
//返回對尾元素
T& Back();
//判斷隊列是否為空
bool Empty();
//返回隊列大小
T Size();
};
//歸納:
//1.插入一個元素:直接將元素插入stack1即可;
//2.刪除一個元素:當stack2不為空時 ,直接彈出棧頂元素,當stack2為空時,將stack1元素逐個彈出並壓入stack2,然后在彈出棧頂元素;
//入隊
template<class T>
void Queue<T>::Push(const T &val)
{
//棧s1做隊列的隊尾,s2做隊列的對頭
s1.push(val);
}
//出隊
template<class T>
void Queue<T>::Pop()
{
if (!s2.empty())
{
s2.pop();
}
//s2為空時,s1中的所有內容逐一出棧壓入s2
else
{
while (!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
//壓入之后,s2的存放順序正好和s1的相反,符合隊列的先進先出,直接s2出棧
if (s2.empty())
{
cout << "隊列為空" << endl;
exit(1);
}
s2.pop();
}
}
//返回隊首元素
template<class T>
T& Queue<T>::Front()
{
if (!s2.empty())
{
return s2.top();
}
//s2為空時,s1中的所有內容逐一出棧壓入s2
else
{
while (!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
//壓入之后,s2的存放順序正好和s1的相反,符合隊列的先進先出
if (s2.empty())
{
cout << "隊列為空" << endl;
exit(1);
}
return s2.top();
}
}
//返回對尾元素
template<class T>
T& Queue<T>::Back()
{
//s1不為空直接取
if (!s1.empty())
{
return s1.top();
}
//s2不為空,把s2中的內容放回s1,然后返回
while (!s2.empty())
{
s1.push(s2.top());
s2.pop();
}
if (!s1.empty())
{
return s1.top();
}
else
{
cout << "隊列為空" << endl;
exit(1);
}
}
//判斷是否為空
template<class T>
bool Queue<T>::Empty()
{
if (s1.empty() && s2.empty())
{
return true;
}
else
{
return false;
}
}
//返回對列尺寸
template<class T>
T Queue<T>::Size()
{
return s1.size() + s2.size();
}
int main()
{
Queue<int> q;
q.Push(1);
q.Push(2);
q.Push(3);
q.Push(4);
q.Push(5);
q.Push(6);
cout << "隊列空否: " << q.Empty() << endl;
cout << "獲取隊頭元素:" << q.Front() << endl;
cout << "獲取隊尾元素: " << q.Back() << endl;
cout << "獲取隊列的大小:" << q.Size() << endl;
cout << "出隊" << endl;
q.Pop();
cout << "獲取隊列的大小:" << q.Size() << endl;
cout << "入隊" << endl;
q.Push(7);
cout << "隊列空否: " << q.Empty() << endl;
cout << "獲取隊頭元素:" << q.Front() << endl;
cout << "獲取隊尾元素: " << q.Back() << endl;
cout << "獲取隊列的大小:" << q.Size() << endl;
cout << "出隊" << endl;
q.Pop();
cout << "獲取隊列的大小:" << q.Size() << endl;
cout << "出隊" << endl;
q.Pop();
cout << "獲取隊列的大小:" << q.Size() << endl;
system("pause");
return 0;
}