用两个栈实现队列(c++实现)

使用两个栈,实现队列的基本功能:push、pop、判断队列是否为空等,实现的代码如下:

#include<iostream>
#include<stack>
#include<ctime>//计算代码所需要的时间
using namespace std;

class MyQueue
{
public:
	stack<int> staIn;
	stack<int> staOut;

	//判断队列是否为空
	bool empty()
	{
		return staIn.empty() && staOut.empty();
	}

	//将数据放进队列
	void push(int x)
	{
		staIn.push(x);
	}

	//将数据从队列中移出
	int pop()
	{
		if (staOut.empty())
		{
			while(!staIn.empty())
			{
				staOut.push(staIn.top());
				staIn.pop();
			}
		}
		int result = staOut.top();
		staOut.pop();
		return result;
	}

	//获取队列的第一个元素
	int peek()
	{
		int result = this->pop();
		staOut.push(result);
		return result;
	}
};

int main()
{
	clock_t starttime, endtime;
	starttime = clock();//计时开始
	MyQueue myqueue;
	for (int i = 1; i < 4; i++)
	{
		myqueue.push(i);
	}
	cout << "队列的第一个数据为:" <<myqueue.peek()<< endl;
	endtime = clock();//计时结束
	cout << "运行时间为: " << (double)(endtime - starttime) / CLOCKS_PER_SEC << "s" << endl;
	system("pause");
	return 0;
}

相关推荐

  1. 实现队列c++实现

    2023-12-07 05:00:02       37 阅读
  2. 队列实现C

    2023-12-07 05:00:02       12 阅读
  3. 实现队列

    2023-12-07 05:00:02       12 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-07 05:00:02       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-07 05:00:02       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-07 05:00:02       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-07 05:00:02       18 阅读

热门阅读

  1. praseInt 和 逻辑或连用

    2023-12-07 05:00:02       28 阅读
  2. SpringMVC常用注解

    2023-12-07 05:00:02       25 阅读
  3. Spring Boot学习(三十三):集成kafka

    2023-12-07 05:00:02       45 阅读
  4. RK3288升级WebView版本,替换webview app

    2023-12-07 05:00:02       35 阅读
  5. android 13.0 Camera2去掉前置摄像头闪光灯功能

    2023-12-07 05:00:02       36 阅读
  6. ThreadLocal+TaskDecorator实现父子线程 参数传递

    2023-12-07 05:00:02       37 阅读
  7. 【无标题】

    2023-12-07 05:00:02       47 阅读
  8. a href自定义下载文件名

    2023-12-07 05:00:02       42 阅读
  9. 设计模式&委派模式(Delegate Pattern)

    2023-12-07 05:00:02       33 阅读
  10. 【LeetCode】258. 各位相加

    2023-12-07 05:00:02       36 阅读
  11. Vue中的组件通信:从子到父的数据传递

    2023-12-07 05:00:02       40 阅读