# Implement heap using stack data structure

I want to implement a heap using the stack data structure. I have searched a lot on the internet. But I do not get any clue how to implement it.

Can you please help me to implement a heap using the stack data structure? The pseudo-code is well enough. I can implement the rest.

• Sounds more challenging than the other way around. Please add, for the purpose of this question, the operations stack provides as well as those required from heap. Add property requirements as needed. – greybeard Nov 16 '19 at 9:17
• Why do you want to do this? I'm finding it hard to see why you wouldn't just implement a heap as a heap or in an array, unless it's a homework exercise. – David Richerby Nov 16 '19 at 9:50
• It is previous admission test question of my university which I want to solve – Sagor Nov 16 '19 at 12:51
• Please mention which heap operations need to be implemented and which stack operations are available. It might not be possible to implement all the standard min-heap operations (including insert) if only one stack is available for storage. – Ashwin Ganesan Nov 18 '19 at 9:33

The data structure consists of single stack $$S$$ that will contain the elements of the heap.
Make-heap$$(A)$$: To build a heap from a set of elements $$A$$, sort $$A$$ in nonincreasing order and push the elements one by one into $$S$$ (according to their order). In this way the last element to be pushed into the stack will be one of the minimums of $$A$$. This requires $$O(|A| \log |A|)$$ time.
Top: Return the top element of $$S$$ (in $$O(1)$$ time).
Pop: Pop the top element $$x$$ from $$S$$ (in $$O(1)$$ time). Return $$x$$.
Push$$(x)$$: To push a new element $$x$$ into the min-heap proceed as follows: create a new temporary stack $$T$$; while the top element $$y$$ of $$S$$ is smaller than $$x$$, pop $$y$$ from $$S$$ and push it into $$T$$; Finally, push $$x$$ into $$S$$ and iteratively pop the elements from $$T$$ while pushing them into $$S$$. When $$T$$ is empty you are done. Sadly, this requires $$O(|S|)$$ time in the worst case.