添加0225.用队列实现栈/0232.用栈实现队列 Java版本。

This commit is contained in:
LehiChiang
2021-05-12 22:56:39 +08:00
parent d5b378e142
commit 49eed9c8a3
2 changed files with 107 additions and 5 deletions

View File

@ -154,9 +154,58 @@ public:
## 其他语言版本 ## 其他语言版本
Java Java
```java
class MyStack {
Queue<Integer> queue1; // 和栈中保持一样元素的队列
Queue<Integer> queue2; // 辅助队列
/** Initialize your data structure here. */
public MyStack() {
queue1 = new LinkedList<>();
queue2 = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
queue2.offer(x); // 先放在辅助队列中
while (!queue1.isEmpty()){
queue2.offer(queue1.poll());
}
Queue<Integer> queueTemp;
queueTemp = queue1;
queue1 = queue2;
queue2 = queueTemp; // 最后交换queue1和queue2将元素都放到queue1中
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return queue1.poll(); // 因为queue1中的元素和栈中的保持一致所以这个和下面两个的操作只看queue1即可
}
/** Get the top element. */
public int top() {
return queue1.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return queue1.isEmpty();
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
```
Python Python

View File

@ -19,7 +19,7 @@ push(x) -- 将一个元素放入队列的尾部。
pop() -- 从队列首部移除元素。 pop() -- 从队列首部移除元素。
peek() -- 返回队列首部的元素。 peek() -- 返回队列首部的元素。
empty() -- 返回队列是否为空。 empty() -- 返回队列是否为空。
 
示例: 示例:
@ -129,9 +129,62 @@ public:
## 其他语言版本 ## 其他语言版本
Java Java
```java
class MyQueue {
Stack<Integer> stack1;
Stack<Integer> stack2;
/** Initialize your data structure here. */
public MyQueue() {
stack1 = new Stack<>(); // 负责进栈
stack2 = new Stack<>(); // 负责出栈
}
/** Push element x to the back of queue. */
public void push(int x) {
stack1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
dumpStack1();
return stack2.pop();
}
/** Get the front element. */
public int peek() {
dumpStack1();
return stack2.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return stack1.isEmpty() && stack2.isEmpty();
}
// 如果stack2为空那么将stack1中的元素全部放到stack2中
private void dumpStack1(){
if (stack2.isEmpty()){
while (!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
```
Python Python