Monday, August 28th

 Stack queues

Implement a stack using queues.  The implementation includes methods for pushing, popping, finding the front element (top) and returning empty status.

Photo courtesy of Sju.  Distributed via Wikipedia under the Creative Commons Attribution-Share Alike 3.0 Unported license.  No changes made.

The beginning of the problem states to use 2 queues.  At the end of the problem, Leetcode challenges one to come up with a solution using 1 queue.  The solution here is for 1 queue, which exercises similar ideas.

For my approach, I used 1 queue to implement pushing in constant time and pop/top in O(n).

To initialize the stack, we create an empty queue.  The queue q is a global variable.

    MyStack() {
        q=queue<int>();
    }

For pushing, we simply push the inputted element to the back of the queue

    void push(int x) {
        q.push(x);    
}

The idea behind pop and front is the same.  Iterate over all elements from the front of the queue, save the last element.  All the elements before the last element, pop them from the front of the queue, then push them to the back of the queue.  When the last element is reached, set the variable equal to x and pop it from the front of the queue. 

If the operation is to find the top(), then push the popped element to the back of the queue.  If the operation is to pop the element, then do not push it back onto the queue.  Either way, return x.

    int pop() {
        int x, qsize;
        qsize=q.size();
        for(int i=0; i<qsize-1; i++) {
            x=q.front();
            q.pop();
            q.push(x);
        } 
        x=q.front();
        q.pop();
        return x;
    }
    
    int top() {
        int x, qsize;
        qsize=q.size();
        for(int i=0; i<qsize-1; i++) {
            x=q.front();
            q.pop();
            q.push(x);
        } 
        x=q.front();
        q.pop();
        q.push(x);
        return x;
    }

Finally, to test emptiness, just return whether or not the queue is empty

    bool empty() {
        if(q.empty()) return true;
        else return false;
    }

This was a stack implemented with 1 queue, using constant time pushes and linear time top/front.  It is also possible to use a similar approach to implement pushes in linear time and top/front in constant time.  This would save some code, as top/front would only be a couple lines, with most code going to the push.  Two functions would be constant time, rather than two being linear time.  Either way they both work and run in as low as 0 ms.


Comments

Popular posts from this blog

Wednesday, September 20th

Monday, September 11th

Tuesday, September 19th