博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
232. Implement Queue using Stacks Java Solutions
阅读量:5162 次
发布时间:2019-06-13

本文共 1681 字,大约阅读时间需要 5 分钟。

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 top, size, 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).

to see which companies asked this question

 
1 class MyQueue { 2     Stack
s1 = new Stack
(); 3 Stack
s2 = new Stack
(); 4 // Push element x to the back of queue. 5 public void push(int x) { 6 s1.push(x); 7 } 8 9 // Removes the element from in front of queue.10 public void pop() {11 if(!s2.isEmpty()) s2.pop();12 else{13 while(!s1.isEmpty()) s2.push(s1.pop());14 s2.pop();15 }16 }17 18 // Get the front element.19 public int peek() {20 if(!s2.isEmpty()) return s2.peek();21 else{22 while(!s1.isEmpty()) s2.push(s1.pop());23 return s2.peek();24 }25 }26 27 // Return whether the queue is empty.28 public boolean empty() {29 return s1.isEmpty() && s2.isEmpty();30 }31 }

 

转载于:https://www.cnblogs.com/guoguolan/p/5453031.html

你可能感兴趣的文章
JDBC——释放资源的代码
查看>>
bootstrap模态框垂直居中
查看>>
用数据管理过程(3)——可预测级别的量化管理(麦当劳的管理方式)
查看>>
DataGridView的Validating事件注册后删除操作的处理
查看>>
我的IOS学习历程-第七天
查看>>
json的两种表示结构(对象和数组).。
查看>>
iOS Undefined symbols for architecture xxx问题的总结
查看>>
bzoj 3685: 普通van Emde Boas树
查看>>
关于线程池,那些你还不知道的事
查看>>
二分类问题F-score评判指标(转载)
查看>>
JAVA基础之字符串和面向对象
查看>>
大数据R语言简析
查看>>
Ant自己主动编译打包&公布 android项目
查看>>
vc6编译stlport及常见问题
查看>>
week_one-python格式化输出
查看>>
Webservice 从客户端中检测到有潜在危险的 request.form值[解决方法]
查看>>
LNMP详细介绍
查看>>
素数判定算法
查看>>
那些文章
查看>>
AR增强现实席卷而来
查看>>