Implementing Queue Using Stack

Question: How would you use stacks to implement a queue?
Answer: So how could we go about doing this? What if we used two stacks and used one as the incoming stack and the other as the outgoing stack? A queue is a FIFO structure, so when we enqueue something, we need to make sure that it does not get popped off before something that was already there. Similarly, when we dequeue something, we have to make sure that elements that were inserted earlier get ejected first.

What’s better than some code!
 
Stack in;
Stack out;
void enqueue( int value ) {
    while( !out.isEmpty() ) {
        in.push( out.pop() );
    }
    in.push( value );
}

int dequeue() {
    while( !in.isEmpty() ) {
        out.push( in.pop() );
    }
    return out.pop();
}

Isn’t that cool? Help share this on Facebook and Twitter!

Comments

Popular posts from this blog

AGRICULTURAL SCIENTIST RECRUITMENT BOARD

CIVIL SERVICES' (I.A.S.) EXAMINATION

HSC Exam Time Table 2013 Arts, Commerce, Science