225. Implement stacks with queues
Posted on April 21, 2023, 4:49 p.m. by Beth Tyler
Category:
reading
Tag:
algorithm
class MyStack {
QueueInteger queue = new LinkedList();
QueueInteger helper = new LinkedList();
public MyStack(a) {}public void push(int x) {
queue.offer(x);
}
public int pop(a) {
int tmp = 0;
while (queue.size() 1) {
tmp = queue.poll();
helper.offer(tmp);
}
// The element to pop on the stack, the end of the queue, is no longer put in the helper queue, only poll
tmp = queue.poll();
// The helper goes to queue
while(! helper.isEmpty()) { queue.offer(helper.poll()); }return tmp;
}
public int top(a) {
int tmp = 0;
while(! queue.isEmpty()) { tmp = queue.poll(); helper.offer(tmp); }// The helper goes to queue
while(! helper.isEmpty()) { queue.offer(helper.poll()); }return tmp;
}
public boolean empty(a) {
returnqueue.isEmpty(); }}Copy the code