GoConqr has a new look! Let us know what you think.

Flashcards

Queue from Stack

Suhas S English 1 card

Cards in this deck (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

Information

Description
Flashcards on Queue from Stack, created by Suhas S on 13/05/2018.
Created by
Suhas S
Views
0
Rating

Feedback

What is it about?

What do you think of the new look?

How do you like it?