博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
232用栈实现队列
阅读量:4598 次
发布时间:2019-06-09

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

使用栈实现队列的下列操作:

push(x) -- 将一个元素放入队列的尾部。

pop() -- 从队列首部移除元素。
peek() -- 返回队列首部的元素。
empty() -- 返回队列是否为空。

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/implement-queue-using-stacks

1 import java.util.Stack; 2  3 public class StackForQueue { 4     private Stack
outStack = new Stack<>(); 5 private Stack
inStack = new Stack<>(); 6 public StackForQueue() { 7 8 } 9 10 public void push(int x) {11 inStack.push(x);12 }13 14 public int pop() {15 if(outStack.isEmpty()) {16 while(!inStack.isEmpty()) {17 outStack.push(inStack.pop());18 } 19 }20 return outStack.pop();21 }22 23 public int peek() {24 if(outStack.isEmpty()) {25 while(!inStack.isEmpty()) {26 outStack.push(inStack.pop());27 } 28 }29 return outStack.peek();30 }31 32 public boolean empty() {33 return inStack.isEmpty() && outStack.isEmpty();34 }35 }

 

转载于:https://www.cnblogs.com/xiyangchen/p/11173659.html

你可能感兴趣的文章
centos7 安装中文编码
查看>>
POJ - 3683 Priest John's Busiest Day
查看>>
正则表达式start(),end(),group()方法
查看>>
vuejs 学习旅程一
查看>>
javascript Date
查看>>
linux常用命令2
查看>>
狼图腾
查看>>
13、对象与类
查看>>
Sublime Text3 个人使用心得
查看>>
jquery 编程的最佳实践
查看>>
MeetMe
查看>>
IP报文格式及各字段意义
查看>>
(转载)rabbitmq与springboot的安装与集成
查看>>
C2. Power Transmission (Hard Edition)(线段相交)
查看>>
STM32F0使用LL库实现SHT70通讯
查看>>
Atitit. Xss 漏洞的原理and应用xss木马
查看>>
MySQL源码 数据结构array
查看>>
(文件过多时)删除目录下全部文件
查看>>
T-SQL函数总结
查看>>
python 序列:列表
查看>>