对堆栈进行排序
我知道如何对数组进行排序,但我以前没有对堆栈进行排序。 所以请帮忙。如何使用快速排序算法对堆栈进行排序? 谢谢。
I know how to sort an array but I haven't sorted a stack before.
So please help. How can I sort a stack using the quicksort algorithm?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
“对堆栈进行排序”是什么意思?堆栈的整体思想是遵循后进先出 (LIFO) 顺序。使用堆栈的事物期望它们放入堆栈的最新事物将位于堆栈的顶部,较旧的事物位于其下方,按照它们插入的时间反向排序,因为这就是堆栈。如果你对堆栈进行排序,你就会破坏它。
What do you mean by "sorting a stack"? The whole idea of a stack is that it is in last-in, first-out (LIFO) order. Things that use stacks expect the most recent thing they put on the stack will be at the top of the stack with older things below it, ordered in reverse by when they were inserted because that's what stacks are. If you sort the stack you're going to break that.
最有效的解决方案可能是将数据结构更改为允许随机访问的列表,然后对列表进行排序。即,像这样:
如果您绝对不想使用列表,您可能会发现这个解决方案很有趣。 (盗自此处):
The most efficient solution is probably to change the data structure to a list which allows random access and then sort the list. I.e., something like this:
If you absolutely don't want to use a list, you'll perhaps find this solution interesting. (Stolen from here):
你可以做的是..使用递归,递归地弹出堆栈中的元素,然后找到插入当前元素的最佳位置。如果您需要代码,请告诉我,但是如前面的评论中所述,对堆栈进行排序是完全没有根据的:) :)
What you can do is.. use recursion, recursively pop the elements in the stack and then find the best place to insert the current element. Let me know if you need the code, but then sorting a stack is totally unwarranted as mentioned in the earlier comments :) :)
我编写了这个函数来使用 O(n) 空间对堆栈进行排序。这工作得很好。我将不胜感激任何及时的改进。现在是 O(n*n) 。
I wrote this function to sort the stack using O(n) space. This works perfectly fine. I would appreciate any improvements in time. It's O(n*n) right now.