Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Implement stack using priority queue?

Tags:

algorithm

How to Implement stack using priority queue?

Guys this is a Microsoft Interview Question for Software Engineer/Developer.I just can't make out the meaning of the question.So I goggled and found this:

Stacks and queues may be modeled as particular kinds of priority queues. In a stack, the priority of each inserted element is monotonically increasing; thus, the last element inserted is always the first retrieved.

So what this question wants us to do.As stacks (Correct me if am wrong) are implicitly implemented as priority queues (priority being monotonically increasing as elements are added).

Does anybody can make out the meaning of this question.What we are supposed to do when such type of question is asked in an interview.

like image 343
Algorithmist Avatar asked Feb 02 '11 10:02

Algorithmist


People also ask

How a priority queue can be used to implement a stack?

Solution: In priority queue, we assign priority to the elements that are being pushed. A stack requires elements to be processed in Last in First Out manner. The idea is to associate a count that determines when it was pushed. This count works as a key for the priority queue.

How can we implement a queue using a priority queue?

Implementation of Priority Queue Priority queue can be implemented using an array, a linked list, a heap data structure, or a binary search tree. Among these data structures, heap data structure provides an efficient implementation of priority queues.

Can you use a stack as a minimum priority queue?

You can implement a stack using a priority queue( say PQ) using min heap. You need one extra integer variable (say t). 't' will be used as the priority while inserting/deleting the elements from PQ.


1 Answers

Pseudocode:

// stack of Key
class Stack {
    class Element { int prio, Key elem; };
    MaxPriorityQueue<Element> q;
    int top_priority = 0;

    void push(Key x) { q.push(Element(top_priority++, x)); }
    Key pop() { top_priority--; return q.pop().elem; }
};

LIFO behavior follows from the fact that every new element is pushed with a priority higher than all the current elements, so it will be popped before any of them.

There are two ways to respond to this interview question. One is to explain in detail the structure above. The second is to briefly mention it, mumble something about O(lg n) and say you'd never implement a stack this way.

like image 197
Fred Foo Avatar answered Sep 16 '22 12:09

Fred Foo