題目:用隊列實現棧
使用隊列實現棧的下列操作:
push(x) -- 元素 x 入棧
pop() -- 移除棧頂元素
top() -- 獲取棧頂元素
empty() -- 返回棧是否爲空
Code(JAVA):
package cn.leetcode.study.stack;
import java.util.LinkedList;
import java.util.Queue;
public class MyStack {
private Queue<Integer> queue;
/**
* Initialize your data structure here.
*/
public MyStack() {
queue = new LinkedList<>();
}
/**
* Push element x onto stack.
*/
public void push(int x) {
queue.add(x);
for (int i = 1; i < queue.size(); i++)
queue.add(queue.remove());
}
/**
* Removes the element on top of the stack and returns that element.
*/
public int pop() {
return queue.poll();
}
/**
* Get the top element.
*/
public int top() {
return queue.peek();
}
/**
* Returns whether the stack is empty.
*/
public boolean empty() {
return queue.size() == 0;
}
}
比較簡單啦!
感謝您的支持,請關注作者公衆號: