码迷,mamicode.com
首页 > 编程语言 > 详细

LeetCode-232 Implement Queue using Stacks Solution (with Java)

时间:2020-03-02 15:07:09      阅读:68      评论:0      收藏:0      [点我收藏+]

标签:void   epc   push   example   return   structure   nbsp   strong   http   

1. Description:

技术图片

Notes: 技术图片

2. Examples:

技术图片

3.Solutions:

 1 /**
 2  * Created by sheepcore on 2019-03-07
 3  * Your MyQueue object will be instantiated and called as such:
 4  * MyQueue obj = new MyQueue();
 5  * obj.push(x);
 6  * int param_2 = obj.pop();
 7  * int param_3 = obj.peek();
 8  * boolean param_4 = obj.empty();
 9  */
10 class MyQueue {
11     /** Initialize your data structure here. */
12     Stack<Integer> input = new Stack<Integer>();
13     Stack<Integer> output = new Stack<Integer>();
14 
15     /** Push element x to the back of queue. */
16     public void push(int x) {
17         input.push(x);
18     }
19 
20     /** Removes the element from in front of queue and returns that element. */
21     public int pop() {
22         peek();
23         return output.pop();
24     }
25 
26     /** Get the front element. */
27     public int peek() {
28        if(output.empty()){
29            while (!input.empty()){
30                output.push(input.pop());
31            }
32        }
33        return output.peek();
34     }
35 
36     /** Returns whether the queue is empty. */
37     public boolean empty() {
38         return input.empty() && output.empty();
39     }
40 }

 

LeetCode-232 Implement Queue using Stacks Solution (with Java)

标签:void   epc   push   example   return   structure   nbsp   strong   http   

原文地址:https://www.cnblogs.com/sheepcore/p/12395208.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!