简体   繁体   English

如何使用优先级队列实现堆栈?

[英]How to implement a stack using a priority queue?

A priority queue is used to implement a stack that stores characters. 优先级队列用于实现存储字符的堆栈。

Push(C) is used to implement Insert(Q,C,K) where K is the appropriate key chosen by the implementation. Push(C)用于实现Insert(Q,C,K) ,其中K是实现选择的适当键。

Pop is implemented as Delete_Min(Q) ,for a sequence of operations in what order must the keys be chosen , strictly decreasing or strictly increasing ? PopDelete_Min(Q) ,对于一系列操作,必须按什么顺序选择键,严格减少还是严格增加?

Let me begin by saying that priority queue and stack are two completely different data structures with different uses and applications. 首先,我要说优先级队列和堆栈是两个完全不同的数据结构,具有不同的用途和应用程序。 One can not always be used to implement the other. 一个不能总是用来实现另一个。

Yes, there are instances where a data structure can be defined in terms of another: for example you can create a stack or queue using a linked list (quite trivially actually), however implementing a stack using a priority queue will not always work. 是的,在某些情况下可以用另一种方式定义数据结构:例如,您可以使用链表创建堆栈或队列(实际上很少),但是使用优先级队列实现堆栈并不总是可行。 Why? 为什么?

Because a stack is first in last out. 因为堆栈是先进先出。 The last thing you push on a stack WILL be the first thing to pop out. 您压入堆栈的最后一件事将是弹出的第一件事。 A stack's sole job is to keep the order of pushed items intact and pop in the reverse order. 堆栈的唯一工作是保持推送项目的顺序不变,并以相反的顺序弹出。

A priority queue however, will always give you the minimum (or maximum based on implementation) with a pop. 但是,优先级队列总是会弹出弹出框,为您提供最小值(或最大值,取决于实现)。 A priority queue will have to -by definition- restructure itself to always maintain the "heap property". 优先级队列将必须(根据定义)对其自身进行重组,以始终保持“堆属性”。 This means the original order in which you pushed will not necessarily be preserved. 这意味着您推送的原始顺序不一定会保留。

Now, your question should be phrased as "In what situation will a priority queue and a stack behave the same way?" 现在,您的问题应表述为“在什么情况下优先级队列和堆栈的行为相同?”

You mentioned your priority queue pop() will delete the minimum value from your queue which indicates you have a min-heap at hand. 您提到优先级队列pop()将从队列中删除最小值,这表明您手头有一个最小堆。 In this scenario the only case where a series of pops from priority queue will resemble those that of a stack, would be when the items were all pushed in non-increasing order. 在这种情况下,优先级队列中的一系列弹出消息与堆栈中的弹出消息类似的唯一情况是,所有项目均以非递增顺序被推送。 It does not have to be strictly decreasing. 它不必严格减少。 (think about pushing all of the same values). (考虑将所有相同的值推入)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM