如何在C++中返回栈底元素?
我正在尝试向我的“堆栈”类添加一个附加方法,该方法将返回堆栈中的底部元素。然而..我只是很难理解这个问题。这是我迄今为止在 stack.cpp 中的代码,但它无法正常工作:
bool Stack::bot(StackItemType& stackBottom){
if (isEmpty()) return false;
StackItems *temp = top;
while (temp != NULL) {
temp = temp->below;
}
stackBottom = temp->item;
return true;
} // end bottom
有帮助吗?谢谢。
I'm trying to add an additional method to my 'stack' class that will return the bottom element in the stack. However.. I'm just having trouble wrapping my head around this one. This is the code I have so far in my stack.cpp, but it's not working correctly:
bool Stack::bot(StackItemType& stackBottom){
if (isEmpty()) return false;
StackItems *temp = top;
while (temp != NULL) {
temp = temp->below;
}
stackBottom = temp->item;
return true;
} // end bottom
Any help ? Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
堆栈设计为仅暴露其顶部。就你而言,它没有“底部”。如果您想访问集合的两端,请不要使用堆栈! (也许您更喜欢双端队列或列表?)
A stack is designed to expose only its top. It has no "bottom" as far as you are concerned. Don't use a stack if you want to access both ends of a collection! (Perhaps you'd prefer a double-ended queue or a list?)
您是否考虑过使用另一种数据结构。堆栈确实不适合这样做。不过,我不会成为一个混蛋而不回答你的问题。
乍一看,您的代码在逻辑上是合理的,假设您使用链接列表实现堆栈并向其添加将元素推送到列表头部。您的代码的问题是 temp 在离开 while 循环时为空。尝试访问空指针是一个错误。
如果将 while 条件更改为使用 temp->below != NULL,则 temp 将在离开 while 循环之前指向有效元素。
Have you considered using another data structure. A stack really isn't meant to do this. However, I'm not going to be a doochebag and not answer you question.
At first glance, your code is logically sound, assuming you're implementing your stack with a linked list and adding to it pushes an element at the head of the list. The problem with your code is that temp is null the moment it leaves the while loop. Attempting to access a null pointer is an error.
If you change your while condition to use temp->below != NULL, then temp would point to a valid element before leaving the while loop.
我认为你必须这样做
但是堆栈是后进先出的。这里不是:p
I think you have to do
But a stack is a LIFO. Here it's not :p
鉴于您使用链接列表作为底层存储,我只需在每次推送到空堆栈时设置底部指针,并在弹出最后一项时取消设置它。
如果您使用数组(希望是动态的)作为底层存储,您只需索引第一项即可。
Given that you are using a linked list as the underling storage, I would simply set the the bottom pointer every time you push to a empty stack, and unset it anytime you pop the last item.
Were you using an array (hopefully dynamic) for the underling storage you would simply index the first item.