C++中用两个标准容器stack,实现一个队列的方法详解
2019/7/10 23:25:46
本文主要是介绍C++中用两个标准容器stack,实现一个队列的方法详解,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
代码如下所示:
// StackToQueue.cpp : 定义控制台应用程序的入口点。
//用两个标准容器stack,实现一个队列
#include "stdafx.h"
#include <iostream>
#include <stack>
using namespace std;
template <class T>
class StackToQueue
{
public:
StackToQueue()
{
stack1;
stack2;
}
void push(T e)
{
while (!stack2.empty())
{
T temp;
temp = stack2.top();
stack2.pop();
stack1.push(temp);
}
stack2.push(e);
while (!stack1.empty())
{
T temp;
temp = stack1.top();
stack1.pop();
stack2.push(temp);
}
}
void pop()
{
stack2.pop();
}
T front()
{
if (!empty())
{
return stack2.top();
}
else
{
return NULL;
}
}
bool empty()
{
return stack2.empty();
}
size_t size()
{
return stack2.size();
}
private:
stack<T> stack1, stack2;
};
int _tmain(int argc, _TCHAR* argv[])
{
StackToQueue<int> queue;
int i(0);
cout << "Enter several integer number,and press ctrl+z to the end." << endl;
while (cin >> i)
{
queue.push(i);
}
cout << "The front element is: " << queue.front() << endl;
cout << "The size now is: " << queue.size() << endl;
if (!queue.empty())
{
cout << "Pop one element now." << endl;
queue.pop();
}
cout << "The front element is: " << queue.front() << endl;
cout << "The size now is: " << queue.size() << endl;
return 0;
}
复制代码 代码如下:
// StackToQueue.cpp : 定义控制台应用程序的入口点。
//用两个标准容器stack,实现一个队列
#include "stdafx.h"
#include <iostream>
#include <stack>
using namespace std;
template <class T>
class StackToQueue
{
public:
StackToQueue()
{
stack1;
stack2;
}
void push(T e)
{
while (!stack2.empty())
{
T temp;
temp = stack2.top();
stack2.pop();
stack1.push(temp);
}
stack2.push(e);
while (!stack1.empty())
{
T temp;
temp = stack1.top();
stack1.pop();
stack2.push(temp);
}
}
void pop()
{
stack2.pop();
}
T front()
{
if (!empty())
{
return stack2.top();
}
else
{
return NULL;
}
}
bool empty()
{
return stack2.empty();
}
size_t size()
{
return stack2.size();
}
private:
stack<T> stack1, stack2;
};
int _tmain(int argc, _TCHAR* argv[])
{
StackToQueue<int> queue;
int i(0);
cout << "Enter several integer number,and press ctrl+z to the end." << endl;
while (cin >> i)
{
queue.push(i);
}
cout << "The front element is: " << queue.front() << endl;
cout << "The size now is: " << queue.size() << endl;
if (!queue.empty())
{
cout << "Pop one element now." << endl;
queue.pop();
}
cout << "The front element is: " << queue.front() << endl;
cout << "The size now is: " << queue.size() << endl;
return 0;
}
这篇关于C++中用两个标准容器stack,实现一个队列的方法详解的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-12-27Nacos多环境配置学习入门
- 2024-12-27Nacos快速入门学习入门
- 2024-12-27Nacos快速入门学习入门
- 2024-12-27Nacos配置中心学习入门指南
- 2024-12-27Nacos配置中心学习入门
- 2024-12-27Nacos做项目隔离学习入门
- 2024-12-27Nacos做项目隔离学习入门
- 2024-12-27Nacos初识学习入门:轻松掌握服务发现与配置管理
- 2024-12-27Nacos初识学习入门:轻松掌握Nacos基础操作
- 2024-12-27Nacos多环境配置学习入门