如何计算特定项目从堆栈中弹出的次数?
我有一堆元素,必须从中删除一个随机元素(即顶部和该特定元素之间的所有元素将被弹出并再次推送)。每次弹出一个元素时,我们都必须确定其他元素之前已弹出该元素的次数。
我已经关注这个问题很久了。 (堆栈是动态的(即不时添加和删除元素))。
I have a stack of elements from which a random element has to be removed (i.e. all the elements which are between the top and that particular element will be popped and pushed again). And every time an element is popped, we have to determine how many times it has been popped earlier for other elements.
I have been on this since a long while. (The stack is dynamic (i.e. elements are being added and removed from time to time)).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我理解正确,那么您有自己的堆栈结构,并且想要计算特定元素的推送和弹出次数。如果是这种情况,您可以将数据包装在
struct
中,并让堆栈存储此struct
的列表(无论堆栈的内部实现是什么):If I'm understanding you right, you have your own stack structure and you want to count the pushes and pops of specific elements. If that's the case, you could wrap your data in a
struct
and have the stack store a list (whatever the internal implementation of the stack is) of thisstruct
:我将堆栈存储为单链表,并在每个节点中保留一个整数来表示它被访问的次数。 IE 中,顶部有 5 个、底部有 7 个且没有进行访问的堆栈如下所示:
然后您可以编写自己的 pop (O(n)),它只是迭代链表,为每个节点的访问计数添加 1访问(如果你可以假设你弹出的内容总是在堆栈中,那么你只需要迭代它一次,否则你可能需要迭代两次)这样 pop(3): // Returns 0
pop(7 ): // 返回 0
pop(2): // 返回 2
Push(6):
pop(1): // 返回 1
pop(6): // 返回 1
pop(5): // 返回 4
I would store the stack as a singly linked list, and keep an integer in each node to represent the number of times it's been accessed. IE, a stack with 5 on top, 7 on the bottom and no accesses made would look like:
Then you could write your own pop (O(n)) which just iterates through the linked list adding 1 to access count for each node it visits (if you can assume that what you pop is always in the stack, then you only need to iterate through it once, if not you may need to iterate through twice) such that pop(3): // Returns 0
pop(7): // Returns 0
pop(2): // Returns 2
push(6):
pop(1): // Returns 1
pop(6): // Returns 1
pop(5): // Returns 4