mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Update 0225.用队列实现栈.md
为使用两个 Queue 实现添加新方法,方法将q1作为主要的队列,其元素排列顺序和出栈顺序相同,q2仅作为临时放置,push方法中在加入元素时先将q1中的元素依次出栈压入q2,然后将新加入的元素压入q1,再将q2中的元素依次出栈压入q1,其他方法可直接使用Queue中已有的方法。
This commit is contained in:
@ -166,7 +166,7 @@ public:
|
||||
|
||||
Java:
|
||||
|
||||
使用两个 Queue 实现
|
||||
使用两个 Queue 实现方法1
|
||||
```java
|
||||
class MyStack {
|
||||
|
||||
@ -208,6 +208,42 @@ class MyStack {
|
||||
}
|
||||
|
||||
```
|
||||
使用两个 Queue 实现方法2
|
||||
```java
|
||||
class MyStack {
|
||||
//q1作为主要的队列,其元素排列顺序和出栈顺序相同
|
||||
Queue<Integer> q1 = new ArrayDeque<>();
|
||||
//q2仅作为临时放置
|
||||
Queue<Integer> q2 = new ArrayDeque<>();
|
||||
|
||||
public MyStack() {
|
||||
|
||||
}
|
||||
//在加入元素时先将q1中的元素依次出栈压入q2,然后将新加入的元素压入q1,再将q2中的元素依次出栈压入q1
|
||||
public void push(int x) {
|
||||
while (q1.size() > 0) {
|
||||
q2.add(q1.poll());
|
||||
}
|
||||
q1.add(x);
|
||||
while (q2.size() > 0) {
|
||||
q1.add(q2.poll());
|
||||
}
|
||||
}
|
||||
|
||||
public int pop() {
|
||||
return q1.poll();
|
||||
}
|
||||
|
||||
public int top() {
|
||||
return q1.peek();
|
||||
}
|
||||
|
||||
public boolean empty() {
|
||||
return q1.isEmpty();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
使用两个 Deque 实现
|
||||
```java
|
||||
class MyStack {
|
||||
|
Reference in New Issue
Block a user