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 top
    peek/pop from topsize,
    and is 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;
}
}

最新文章

  1. .Net Core MVC 网站开发(Ninesky) 2.3、项目架构调整-控制反转和依赖注入的使用
  2. NSOperation操作依赖和监听
  3. Linux Shell 网络层监控脚本(监控包括:连接数、句柄数及根据监控反馈结果分析)
  4. RestEasy 3.x 系列之一:Hello world
  5. Windows7下面手把手教你安装Django
  6. Angular ng-repeat
  7. ASP.NET Application,Session,Cookie和ViewState等对象用法和区别 (转)
  8. JavaSE语法基础(3)---函数、数组
  9. 如何上传本地项目到gitHub解决方案
  10. Go 语言多维数组
  11. Mac OS X 10.10优胜美地如何完美接管iphone上的电话和短信
  12. 一幅图,看懂中国CMMI
  13. leetcode刷题第二天&lt;两数相加&gt;
  14. scrapy爬虫框架和selenium的配合使用
  15. vue——router
  16. maven maven-war-plugin 解决java war项目间的依赖(两个war都可独立部署运行,maven 3.2.x亲测)
  17. IOS 上架到App Store被拒的常见问题总结
  18. CPU、OpenGL/DirectorX、显卡驱动和GPU之间的关系
  19. [SQL]卸载数据库清理注册表方法regedit
  20. The Activities of September

热门文章

  1. Node.js 笔记(一) nodejs、npm、express安装
  2. Google Chrome Resize Plugin
  3. format ZKFC失败
  4. keytab生成不了
  5. Unbuntu和Centos中部署同时多版本PHP的详细过程
  6. Linux中Centos7下安装Mysql(更名为Mariadb)
  7. poj - 1191 - 棋盘切割(dp)
  8. ES6学习笔记二:各种扩展
  9. Flash 矢量图和位图性能对比 导出为位图/缓存为位图 export as bitmap / cache as bitmap
  10. JAVA中的CountDownLatch、CyclicBarrier、Semaphore的简单测试