¡GoConqr estrena diseño! Cuéntanos qué te parece.

Fichas

Queue from Stack

Suhas S Inglés 1 ficha

Fichas del conjunto (1)

  1. 1Implement 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 {
    /** Initialize your data structure here. */
    Stack s1;
    Stack s2;
    public MyQueue() {
    s1 = new Stack<>();
    s2 = new Stack<>();
    }
    public void transfer(){
    while(!s1.isEmpty()){
    s2.push(s1.pop());
    }
    }
    /** Push element x to the back of queue. */
    public void push(int x) {
    s1.push(x);
    }
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
    if(s2.isEmpty()){
    transfer();
    }
    return s2.pop();
    }
    /** Get the front element. */
    public int peek() {
    if(s2.isEmpty()){
    transfer();
    }
    return s2.peek();
    }
    /** Returns whether the queue is empty. */
    public boolean empty() {
    return s1.isEmpty() && s2.isEmpty();
    }
    }
    /**
    * Your MyQueue object will be instantiated and called as such:
    * MyQueue obj = new MyQueue();
    * obj.push(x);
    * int param_2 = obj

Información

Descripción
Fichas sobre Queue from Stack, creado por Suhas S el 13/05/2018.
Creado por
Suhas S
Visitas
0
Valoración

Escríbenos

¿Sobre qué es tu mensaje?

¿Qué te parece el nuevo diseño?

¿Te gusta?