(LeetCode)用两个栈实现一个队列
2024-10-16 00:27:42
LeetCode上面的一道题目。原文例如以下:
Implement the following operations of a queue using stacks.
- push(x) -- Push element x to the back of queue.
- pop() -- Removes the element from in front of queue.
- peek() -- Get the front element.
- empty() -- Return whether the queue is empty.
Notes:
- You must use only standard operations of a stack -- which means only
push
,
to toppeek/pop from top
,size
,
andis empty
operations are valid. - Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
- You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
我的思路是创建两个栈S1和S2。入队时。将元素压入S1,出队时,假设栈S2中的元素个数为0,则将S1中的元素一个个压入S2,并弹出最后压入的那个元素。假设栈S2中的元素个数不为0,则直接弹出S2中的顶元素。
代码例如以下:
class MyQueue {
// Push element x to the back of queue.
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int x) {
stack1.push(x);
} // Removes the element from in front of queue.
public void pop() {
if(stack2.size()==0)
{
int m = stack1.size();
for(int i=0;i<m;i++)
{
stack2.push(stack1.pop());
}
}
stack2.pop();
} // Get the front element.
public int peek() {
if(stack2.size()==0)
{
int m = stack1.size();
for(int i=0;i<m;i++)
{
stack2.push(stack1.pop());
}
}
return stack2.peek();
} // Return whether the queue is empty.
public boolean empty() {
return stack1.size()==0&&stack2.size()==0;
}
}
最新文章
- .Net Core MVC 网站开发(Ninesky) 2.3、项目架构调整-控制反转和依赖注入的使用
- NSOperation操作依赖和监听
- Linux Shell 网络层监控脚本(监控包括:连接数、句柄数及根据监控反馈结果分析)
- RestEasy 3.x 系列之一:Hello world
- Windows7下面手把手教你安装Django
- Angular ng-repeat
- ASP.NET Application,Session,Cookie和ViewState等对象用法和区别 (转)
- JavaSE语法基础(3)---函数、数组
- 如何上传本地项目到gitHub解决方案
- Go 语言多维数组
- Mac OS X 10.10优胜美地如何完美接管iphone上的电话和短信
- 一幅图,看懂中国CMMI
- leetcode刷题第二天<;两数相加>;
- scrapy爬虫框架和selenium的配合使用
- vue——router
- maven maven-war-plugin 解决java war项目间的依赖(两个war都可独立部署运行,maven 3.2.x亲测)
- IOS 上架到App Store被拒的常见问题总结
- CPU、OpenGL/DirectorX、显卡驱动和GPU之间的关系
- [SQL]卸载数据库清理注册表方法regedit
- The Activities of September
热门文章
- Node.js 笔记(一) nodejs、npm、express安装
- Google Chrome Resize Plugin
- format ZKFC失败
- keytab生成不了
- Unbuntu和Centos中部署同时多版本PHP的详细过程
- Linux中Centos7下安装Mysql(更名为Mariadb)
- poj - 1191 - 棋盘切割(dp)
- ES6学习笔记二:各种扩展
- Flash 矢量图和位图性能对比 导出为位图/缓存为位图 export as bitmap / cache as bitmap
- JAVA中的CountDownLatch、CyclicBarrier、Semaphore的简单测试