Problem: 225. 用队列实现栈
文章目录
- 题目描述:
- 思路
- Code
题目描述:
思路
1.对一个queue模拟栈的操作,同时用一个int类型的变量topElem记录每次每次队列队尾的元素(也即是模拟stack中的stack的栈顶元素);
2.void push(int x):直接将元素入队,同时用topElem记录该元素;
3.int pop():先将队尾倒数两个元素前的元素出队再入队,再将topElem更新记录尾当前队列的队头元素,再将当前的对头元素出队、入队,最后将当前的对头元素出队返回
4.int top():直接返回topElem即可
5.boolean empty():直接判断队列是否位空即可
Code
class MyStack {
Queue<Integer> queue;
int topElem;
public MyStack() {
queue = new LinkedList<>();
topElem = 0;
}
/**
* Push the element to the queue
*
* @param x The element to be pushed
*/
public void push(int x) {
queue.offer(x);
topElem = x;
}
/**
* Remove the top element of stack
*
* @return int
*/
public int pop() {
int size = queue.size();
//remain tow tail element of queue
while (size > 2) {
queue.offer(queue.poll());
size--;
}
//recode the new tail element
topElem = queue.peek();
queue.offer(queue.poll());
return queue.poll();
}
/**
* Return the tail element of queue
*
* @return int
*/
public int top() {
return topElem;
}
/**
* Check the empty
*
* @return boolean
*/
public boolean empty() {
return queue.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();
*/