(一)Implement Stack using Queues
题目:用队列的方式实现栈的操作;
解答:用两个队列的方式实现;
优化:使用一个队列,但是在push操作时,注意将元素顺序反转:
public void push(int x) {
queue1.offer(x);
for (int i = 1; i <queue.size(); i++) {
queue.add(queue.poll());
}
}
代码:
class MyStack {
Queue<Integer> queue1;
Queue<Integer> queue2;
/** Initialize your data structure here. */
public MyStack() {
queue1 = new LinkedList<Integer>();
queue2 = new LinkedList<Integer>();
}
/** Push element x onto stack. */
public void push(int x) {
queue1.offer(x);
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
int size = queue1.size();
for (int i = 0; i < size - 1; i++) {
int node = queue1.poll();
queue2.offer(node);
}
int res = queue1.poll();
while (!queue2.isEmpty()) {
int node = queue2.poll();
queue1.offer(node);
}
return res;
}
/** Get the top element. */
public int top() {
int size = queue1.size();
for (int i = 0; i < size - 1; i++) {
int node = queue1.poll();
queue2.offer(node);
}
int res = queue1.poll();
queue2.offer(res);
while (!queue2.isEmpty()) {
int node = queue2.poll();
queue1.offer(node);
}
return res;
}
/** Returns whether the stack is empty. */
public boolean empty() {
return queue1.isEmpty();
}
}
(二)Implement Queue using Stacks
https://leetcode.com/problems/implement-queue-using-stacks/description/
题目:使用栈来实现队列的操作;
解答:使用两个栈来实现栈内元素的逆序;
代码:
class MyQueue {
Stack <Integer> stack1;
Stack <Integer> stack2; //store the elements as the queue's order;
/** Initialize your data structure here. */
public MyQueue() {
stack1 = new Stack<Integer>();
stack2 = new Stack<Integer>();
}
/** Push element x to the back of queue. */
public void push(int x) {
while (!stack2.isEmpty()) {
stack1.push(stack2.pop());
}
stack1.push(x);
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
return stack2.pop();
}
/** Get the front element. */
public int peek() {
return stack2.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return stack2.isEmpty();
}
}