博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【LeetCode232】 Implement Queue using Stacks★
阅读量:4618 次
发布时间:2019-06-09

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

1.题目描述

2.思路

  思路简单,这里用一个图来举例说明:

3.java代码

1 public class MyQueue { 2  3    Stack
stack1=new Stack
(); 4 Stack
stack2=new Stack
(); 5 6 /** Push element x to the back of queue. */ 7 public void push(int x) { 8 stack1.push(x); 9 }10 11 /** Removes the element from in front of queue and returns that element. */12 public int pop() {13 if(!stack2.isEmpty())14 return stack2.pop();15 else{16 while(!stack1.empty())17 stack2.push(stack1.pop());18 return stack2.pop();19 }20 }21 22 /** Get the front element. */23 public int peek() {24 if(!stack2.isEmpty())25 return stack2.peek();26 else{27 while(!stack1.empty())28 stack2.push(stack1.pop());29 return stack2.peek();30 }31 }32 33 /** Returns whether the queue is empty. */34 public boolean empty() {35 return stack1.empty()&&stack2.empty();36 }37 }38 39 /**40 * Your MyQueue object will be instantiated and called as such:41 * MyQueue obj = new MyQueue();42 * obj.push(x);43 * int param_2 = obj.pop();44 * int param_3 = obj.peek();45 * boolean param_4 = obj.empty();46 */

 

转载于:https://www.cnblogs.com/zhangboy/p/6558385.html

你可能感兴趣的文章
Docker启动mysql的坑2
查看>>
j2ee爬坑行之二 servlet
查看>>
JAVA基础入门(JDK、eclipse下载安装)
查看>>
最基础的applet运用--在applet上画线
查看>>
并不对劲的hdu4777
查看>>
linux使用rz、sz快速上传、下载文件
查看>>
判断数字的正则表达式
查看>>
DOC常用命令(转)
查看>>
php写一个判断是否有cookie的脚本
查看>>
Mac配置Fiddler抓包工具
查看>>
转:Java并发集合
查看>>
Word截图PNG,并压缩图片大小
查看>>
Python项目对接CAS方案
查看>>
mysql产生随机数
查看>>
编程风格
查看>>
熟悉常用的Linux命令
查看>>
易之 - 我是个大师(2014年3月6日)
查看>>
Delphi中窗体的事件
查看>>
file_get_contents()获取https出现这个错误Unable to find the wrapper “https” – did
查看>>
linux vi编辑器
查看>>