mirror of
https://github.com/chefyuan/algorithm-base.git
synced 2025-08-07 07:42:00 +00:00
test
This commit is contained in:
51
animation-simulation/栈和队列/225.用队列实现栈.md
Normal file
51
animation-simulation/栈和队列/225.用队列实现栈.md
Normal file
@@ -0,0 +1,51 @@
|
||||
# leetcode 255 队列实现栈
|
||||
|
||||
我们昨天实现了如何用两个栈实现队列,原理很简单,今天我们来实现一下如何用队列实现栈。
|
||||
|
||||
其实原理也很简单,我们利用队列先进先出的特点,每次队列模拟入栈时,我们先将队列之前入队的元素都出列,仅保留最后一个进队的元素。
|
||||
|
||||
然后再重新入队,这样就实现了颠倒队列中的元素。比如我们首先入队1,然后再入队2,我们需要将元素1出队,然后再重新入队,则实现了队列内元素序列变成了2,1。
|
||||
|
||||
废话不多说,我们继续看动图
|
||||
|
||||

|
||||
|
||||
下面我们来看一下题目代码,也是很容易理解。
|
||||
|
||||
```java
|
||||
class MyStack {
|
||||
//初始化队列
|
||||
Queue<Integer> queue;
|
||||
public MyStack() {
|
||||
queue = new LinkedList<>();
|
||||
}
|
||||
|
||||
//模拟入栈操作
|
||||
public void push(int x) {
|
||||
queue.offer(x);
|
||||
//将之前的全部都出队,然后再入队
|
||||
for(int i = 1;i<queue.size();i++){
|
||||
queue.offer(queue.poll());
|
||||
}
|
||||
|
||||
}
|
||||
//模拟出栈
|
||||
public int pop() {
|
||||
return queue.poll();
|
||||
|
||||
}
|
||||
|
||||
//返回栈顶元素
|
||||
public int top() {
|
||||
return queue.peek();
|
||||
|
||||
}
|
||||
//判断是否为空
|
||||
public boolean empty() {
|
||||
return queue.isEmpty();
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
Reference in New Issue
Block a user