Implement Queue by Two Stacks & Implement Stack using Queues

时间:2023-03-08 23:27:06
Implement Queue by Two Stacks & Implement Stack using Queues

Implement Queue by Two Stacks

Implement the following operations of a queue using stacks.

  • push(x) -- Push element x to the back of queue.
  • pop() -- Removes the element from in front of queue.
  • peek() -- Get the front element.
  • empty() -- Return whether the queue is empty.
 class MyQueue {

     private Stack<Integer> stack1, stack2;

     public MyQueue() {
// do initialization if necessary
stack1 = new Stack<Integer>();
stack2 = new Stack<Integer>();
} // Push element x to the back of queue.
public void push(int x) {
stack1.push(x);
} // Removes the element from in front of queue.
public void pop() {
if (stack2.isEmpty()) {
while(!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
stack2.pop();
} // Get the front element.
public int peek() {
if (stack2.isEmpty()) {
while(!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.peek();
} // Return whether the queue is empty.
public boolean empty() {
return stack1.isEmpty() && stack2.isEmpty();
}
}
Implement Stack using Queues

  Implement the following operations of a stack using queues.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • empty() -- Return whether the stack is empty.

Notes:

    • You must use only standard operations of a queue -- which means only push to backpeek/pop from frontsize, and is empty operations are valid.
    • Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
    • You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
分析:

用两个queues,第二个queue永远为空,它只用于临时保存数字而已。

 class MyStack {
// Push element x onto stack.
LinkedList<Integer> q1 = new LinkedList<Integer>();
LinkedList<Integer> q2 = new LinkedList<Integer>(); public void push(int x) {
q1.offer(x);
} // Removes the element on top of the stack.
public void pop() {
if (!empty()) {
while(q1.size() >= ) {
q2.offer(q1.poll());
}
q1.poll(); while(q2.size() >= ) {
q1.offer(q2.poll());
}
}
} // Get the top element.
public int top() {
int value = ;
if (!empty()) {
while(q1.size() >= ) {
if (q1.size() == ) {
value = q1.peek();
}
q2.offer(q1.poll());
} while(q2.size() >= ) {
q1.offer(q2.poll());
}
}
return value;
} // Return whether the stack is empty.
public boolean empty() {
return q1.size() == ;
}
}