Leetcode-225. 用队列实现栈
225. 用队列实现栈
使用队列实现栈的下列操作:
push(x) -- 元素 x 入栈
pop() -- 移除栈顶元素
top() -- 获取栈顶元素
empty() -- 返回栈是否为空
注意:
你只能使用队列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 这些操作是合法的。
你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。
运行结果
解题思路
直接用队列实现栈
用一个变量记录栈顶元素,即队尾元素---入队的是队尾
入栈----入队,更新栈顶元素变量
栈顶----返回栈顶元素变量
判空----队空
出栈----先将队列中的(n-2)个元素出队,再入队-----之后倒数第二个元素,记录下新的栈顶元素值,再入队---最后直接出队---即使原来的栈顶元素出栈
java代码
class MyStack {
Queue<Integer> q;
int top_num=0;
/** Initialize your data structure here. */
public MyStack() {
q=new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
q.offer(x);
top_num=x;
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
int size=q.size();
while(size>2){
q.offer(q.poll());
size--;
}
top_num=q.peek();
q.offer(q.poll());
return q.poll();
}
/** Get the top element. */
public int top() {
return top_num;
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/简化的代码--思路几乎一样
class MyStack {
Queue<Integer> q;
int top_num=0;
/** Initialize your data structure here. */
public MyStack() {
q=new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
q.offer(x);
top_num=x;
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
int size=q.size();
while(size>1){
top_num=q.poll();
q.offer(top_num);
size--;
}
return q.poll();
}
/** Get the top element. */
public int top() {
return top_num;
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/Leetcode-牛客-刷题笔记 文章被收录于专栏
本专栏主要用于分享栏主在准备java后端面试过程中的刷题笔记
