LeetCode算法题-Implement Queue Using Stacks(Java实现)
这是悦乐书的第195次更新,第201篇原创
01 看题和准备
今天介绍的是LeetCode算法题中Easy级别的第57题(顺位题号是232)。使用栈实现队列的以下操作。
push(x) - 将元素x推送到队列的后面。
pop() - 从队列前面删除元素。
peek() - 获取前面的元素。
empty() - 返回队列是否为空。
例如:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); //返回1
queue.pop(); //返回1
queue.empty(); //返回false
本次解题使用的开发工具是eclipse,jdk使用的版本是1.8,环境是win7 64位系统,使用Java语言编写和测试。
02 第一种解法
队列的特性是先进先出,而栈的特性是先进后去,在使用栈进行队列的出队列和队顶操作时,需要借助另外一个栈来进行反转然后再还原,而入队列的操作还是无需特殊处理。
class MyQueue {
    private Stack<Integer> stack;
    /** Initialize your data structure here. */
    public MyQueue() {
        stack = new Stack<Integer>();
    }
    /** Push element x to the back of queue. */
    public void push(int x) {
        stack.push(x);
    }
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        Stack<Integer> temp = new Stack<Integer>();
        while (!stack.isEmpty()) {
            temp.push(stack.pop());
        }
        int tem = temp.pop();
        while (!temp.isEmpty()) {
            stack.push(temp.pop());
        }
        return tem;
    }
    /** Get the front element. */
    public int peek() {
        Stack<Integer> temp = new Stack<Integer>();
        while (!stack.isEmpty()) {
            temp.push(stack.pop());
        }
        int tem = temp.peek();
        while (!temp.isEmpty()) {
            stack.push(temp.pop());
        }
        return tem;
    }
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return stack.isEmpty();
    }
}
03 第二种解法
此解法和上面的第一种解法正好相反,是在入队列的时候,借助另外一个栈来进行反转操作,而出队列和获取队列顶的操作可以直接使用栈的方法,无需特殊处理。
class MyQueue2 {
    Stack<Integer> stack;
    /** Initialize your data structure here. */
    public MyQueue2() {
        stack = new Stack<Integer>();
    }
    /** Push element x to the back of queue. */
    public void push(int x) {
        Stack<Integer> temp=new Stack<>();
        while(!stack.isEmpty()){
            temp.push(stack.pop());
        }
        temp.push(x);
        while(!temp.isEmpty()){
            stack.push(temp.pop());
        }
    }
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        return stack.pop();
    }
    /** Get the front element. */
    public int peek() {
        int a = stack.pop();
        stack.push(a);
        return a;
    }
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return stack.isEmpty();
    }
}
04 第三种解法
此解法使用两个栈s1、s2来实现队列的相关操作。
入队列时,如果s2不为空,那么先把s2中的元素pop出来在push进s1,然后才去将当前要插入的数据push进s1。
出队列时,如果s2为空,即此前没有进行出队列操作或者获取队列顶的操作,那么就需要将s1反转,即将s1的元素pop出来,然后push进s2中,此时再返回s2的pop操作即可。如果s2不为空,即说明上一次操作不是入队列,而是出队列或获取队列顶的操作,直接返回s2的pop操作即可。
获取队列顶时,和入队列操作时的判断一致,只不过最后返回s2的peek操作即可。
class MyQueue3 {
    private Stack<Integer> s1;
    private Stack<Integer> s2;
    /** Initialize your data structure here. */
    public MyQueue3() {
        s1 = new Stack<Integer>();
        s2 = new Stack<Integer>();
    }
    /** Push element x to the back of queue. */
    public void push(int x) {
        while(!s2.empty()) {
            s1.push(s2.pop());
        }
        s1.push(x);
    }
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        if (s2.empty()) {
            while (!s1.empty()) {
                s2.push(s1.pop());
            }
        }
        return s2.pop();
    }
    /** Get the front element. */
    public int peek() {
        if (s2.empty()) {
            while (!s1.empty()) {
                s2.push(s1.pop());
            }
        }
        return s2.peek();
    }
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return (s1.empty() && s2.empty());
    }
}
05 第四种解法
在入队列时,始终往第一位插入元素,而其他的出队列、获取队列的顶、判空这些操作都可以直接使用栈的方法,而无需重新实现。
class MyQueue4 {
    private Stack<Integer> stack;
    /** Initialize your data structure here. */
    public MyQueue4() {
        stack = new Stack<Integer>();
    }
    /** Push element x to the back of queue. */
    public void push(int x) {
        stack.add(0, x);
    }
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        return stack.pop();
    }
    /** Get the front element. */
    public int peek() {
        return stack.peek();
    }
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return stack.isEmpty();
    }
}
06 小结
算法专题目前已连续日更超过一个月,算法题文章57+篇,公众号对话框回复【数据结构与算法】、【算法】、【数据结构】中的任一关键词,获取系列文章合集。
以上就是全部内容,如果大家有什么好的解法思路、建议或者其他问题,可以下方留言交流,点赞、留言、转发就是对我最大的回报和支持!
LeetCode算法题-Implement Queue Using Stacks(Java实现)的更多相关文章
- LeetCode算法题-Letter Case Permutation(Java实现)
		
这是悦乐书的第315次更新,第336篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第184题(顺位题号是784).给定一个字符串S,将每个字母单独转换为小写或大写以创建另 ...
 - LeetCode算法题-Reshape the Matrix(Java实现)
		
这是悦乐书的第264次更新,第277篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第131题(顺位题号是566).在MATLAB中,有一个非常有用的函数叫做'reshap ...
 - LeetCode算法题-Implement Stack Using Queues
		
这是悦乐书的第193次更新,第198篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第54题(顺位题号是225).使用队列实现栈的以下操作: push(x) - 将元素x推 ...
 - LeetCode算法题-Subdomain Visit Count(Java实现)
		
这是悦乐书的第320次更新,第341篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第189题(顺位题号是811).像"discuss.leetcode.com& ...
 - LeetCode算法题-Jewels and Stones(Java实现)
		
这是悦乐书的第313次更新,第334篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第182题(顺位题号是771).字符串J代表珠宝,S代表你拥有的石头.S中的每个字符都是 ...
 - LeetCode算法题-Reach a Number(Java实现)
		
这是悦乐书的第310次更新,第331篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第179题(顺位题号是754).你站在无限数字线的0号位置.在目的地有个target.在 ...
 - LeetCode算法题-Shortest Completing Word(Java实现)
		
这是悦乐书的第309次更新,第330篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第178题(顺位题号是748).从给定的字典单词中查找最小长度单词,其中包含字符串lic ...
 - LeetCode算法题-Self Dividing Numbers(Java实现)
		
这是悦乐书的第305次更新,第324篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第173题(顺位题号是728).自分割数是一个可被其包含的每个数字整除的数字.例如,12 ...
 - LeetCode算法题-Find Pivot Index(Java实现)
		
这是悦乐书的第304次更新,第323篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第172题(顺位题号是724).给定一个整数nums数组,编写一个返回此数组的" ...
 
随机推荐
- Bootstrap-table使用总结(整合版)
			
一.什么是Bootstrap-table? 在业务系统开发中,对表格记录的查询.分页.排序等处理是非常常见的,在Web开发中,可以采用很多功能强大的插件来满足要求,且能极大的提高开发效率,本随笔介绍这 ...
 - 业务开发(六)—— MyBatis框架
			
0x01.元素内容必须由格式正确的字符数据或标记组成. Caused by: org.apache.ibatis.builder.BuilderException: Error creating do ...
 - [转]ERROR: http://rancherserver/v1 is not accessible
			
本文转自:http://securityer.lofter.com/post/1d0f3ee7_10c465cc 安装rancher agent时出现以下报错 [root@localhost ~]# ...
 - HttpClient之可恨的Expect(C# http 请求卡住的解决办法)
			
今天用HTTP.HttpClient这个对象开发的时候遇到一个奇怪的问题 当POST一个页面的时候始终卡住提交不成功 最初以为协议有错误就抓包测试在抓包在测试 最后想到是不是HttpClient的BU ...
 - VS2017 启动调试出现  无法启动程序“http://localhost:15613”  操作在当前状态中是非法的。 同时附加进程也是错误的解决方法
			
第一次发表这样的博客,不会如何的排版,还有很多的不懂,大神勿喷哈! 同时是给自己做的一次记录,已方便后面可能会同样出现该问题后不用像无头苍蝇一样到处百度乱找 VS2017 启动调试出现 无法启动程序 ...
 - npm 相关命令
			
npm的相关命令 npm init -y : 产生一个package.json文件 npm install --save-dev 模块名 : 模块名会再package.json文件中的d ...
 - Java web.xml笔记
			
Javaweb项目中, web.xml文件其中的各种设置, 就是简单的标注 <?xml version="1.0" encoding="UTF-8"?&g ...
 - If you did this already, delete the swap file ".git/.MERGE_MSG.swp"
			
出现这种情况一般是不正常退出造成的,找到隐藏文件后删除解决
 - jQuery计算文本宽度和input标签根据输入字符动态自适应宽度的实现
			
jQuery计算文本宽度的原理是利用html提供的<pre>标签,向dom中动态添加<pre>标签,标签里的内容就是要测试长度的文本,获取完长度之后再删除刚才添加的<pr ...
 - angularJS中控制器和作用范围
			
$scope是$rootScope的子作用域控制对象,$rootScope的id为1,其他的为2,3,4... 不同的控制器之间,所对应的作用域控制对象$scope,之间是相互隔离的,如果要共享数据, ...