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

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

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

push(x) – 元素 x 入栈

pop() – 移除栈顶元素
top() – 获取栈顶元素
empty() – 返回栈是否为空
注意:
你只能使用队列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 这些操作是合法的。
你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。
题目链接:
解题思路:
在这里插入图片描述
在这里插入图片描述

class MyStack {
/** Initialize your data structure here. */ private Queue
A=new LinkedList<>(); private Queue
B=new LinkedList<>(); /** Push element x onto stack. */ public void push(int x) {
A.offer(x); } /** Removes the element on top of the stack and returns that element. */ public Integer pop() {
if(empty()){
return null; } while(A.size()>1){
Integer front=A.poll(); B.offer(front); } int ret=A.poll(); swapAB(); return ret; } /** Get the top element. */ public Integer top() {
if(empty()){
return null; } while(A.size()>1){
Integer front=A.poll(); B.offer(front); } int ret=A.poll(); B.offer(ret); swapAB(); return ret; } public void swapAB(){
Queue
tmp=A; A=B; B=tmp; } /** Returns whether the stack is empty. */ public boolean empty() {
return A.isEmpty(); }}

转载地址:http://hflzi.baihongyu.com/

你可能感兴趣的文章
Source Insight 经典教程
查看>>
快速打开菜单附件中的工具
查看>>
Windows系统进程间通信
查看>>
linux exec的用法
查看>>
C语言中如何使用宏
查看>>
Http与RPC通信协议的比较
查看>>
Source Insight的对齐问题
查看>>
ubuntu设置开机默认进入字符界面方法
查看>>
chrome 快捷键
查看>>
Linux下buffer和cache的区别
查看>>
程序员不应该再犯的五大编程错误
查看>>
utf8中文编码范围
查看>>
oracle中文(utf8)按拼音排序的简单解决方案
查看>>
[转载][转帖]Hibernate与Sleep的区别
查看>>
Linux系统的默认编码设置
查看>>
Linux系统调用
查看>>
Linux 信号signal处理机制
查看>>
Linux 信号signal处理函数
查看>>
perror简介
查看>>
signal( SIGINT, SigIntHandler )
查看>>