232. 用栈实现队列

描述

请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):

实现 MyQueue 类:

void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false

 

 

 

链接

232. 用栈实现队列 - 力扣(LeetCode) (leetcode-cn.com)

 

解法:用两个栈 实现

只在 出栈的时候进行 “倒”操作

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

 

题解链接

代码随想录 (programmercarl.com)

 

posted @ 2021-11-26 23:04  DidUStudy  阅读(20)  评论(0编辑  收藏  举报