1、使用隊列實現棧
https://leetcode.com/problems/implement-stack-using-queues/
class MyStack {
private Queue<Integer> queue;
/** Initialize your data structure here. */
public MyStack() {
queue = new LinkedList<Integer>();
}
/** Push element x onto stack. */
public void push(int x) {
Queue<Integer> tempQueue = new LinkedList<Integer>();
tempQueue.offer(x);
while(queue.size() > 0){
tempQueue.offer(queue.poll());
}
queue = tempQueue;
}
/** 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.isEmpty();
}
}
2、用棧實現隊列
2.1、單棧法
https://leetcode.com/problems/implement-queue-using-stacks/
- 除了 push 操作,其他操作就是直接使用棧的操作
- 每次push 平均複雜度都是0(n)
class MyQueue {
private Stack<Integer> stack;
/** Initialize your data structure here. */
public MyQueue() {
stack = new Stack<Integer>();
}
/** Push element x to the back of queue. */
public void push(int x) {
Stack tempStack = new Stack<Integer>();
while(!stack.isEmpty()){
tempStack.push(stack.pop());
}
stack.push(x);
while(!tempStack.isEmpty()){
stack.push((Integer)tempStack.pop());
}
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
return stack.pop();
}
/** Get the front element. */
public int peek() {
return stack.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return stack.isEmpty();
}
}
2.2 雙棧法
- 平均複雜度0(1)
- push 操作直接壓棧 ,pop、peek 都需要判斷 outputStack 爲空的情況
class MyQueue {
private Stack<Integer> inputStack;
private Stack<Integer> outputStack;
/** Initialize your data structure here. */
public MyQueue() {
inputStack = new Stack<Integer>();
outputStack = new Stack<Integer>();
}
/** Push element x to the back of queue. */
public void push(int x) {
inputStack.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if(outputStack.isEmpty()){
while(!inputStack.isEmpty()){
outputStack.push(inputStack.pop());
}
}
return outputStack.pop();
}
/** Get the front element. */
public int peek() {
if(outputStack.isEmpty()){
while(!inputStack.isEmpty()){
outputStack.push(inputStack.pop());
}
}
return outputStack.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return inputStack.isEmpty() && outputStack.isEmpty();
}
}