![](/img/trans.png)
[英]How Can I return second element of stack without pop() function in C++?
[英]How to return bottom element of stack in C++?
我正在尝试向我的“堆栈”class 添加一个附加方法,该方法将返回堆栈中的底部元素。 但是..我只是无法理解这个问题。 这是我目前在我的 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
有什么帮助吗? 谢谢你。
堆栈旨在仅暴露其顶部。 就您而言,它没有“底部”。 如果要访问集合的两端,不要使用堆栈? (也许您更喜欢双端队列或列表?)
您是否考虑过使用另一种数据结构。 堆栈真的不是为了做到这一点。 但是,我不会成为一个傻瓜,也不会回答你的问题。
乍一看,您的代码在逻辑上是合理的,假设您正在使用链表实现堆栈,并向其中添加将一个元素推送到列表的头部。 您的代码的问题是 temp 离开 while 循环的那一刻是 null 。 试图访问 null 指针是一个错误。
如果您将 while 条件更改为使用 temp->below,= NULL。 那么 temp 将在离开 while 循环之前指向一个有效元素。
bool Stack::bot(StackItemType& stackBottom){
if (isEmpty()) return false;
StackItems *temp = top;
while (temp->below != NULL) {
temp = temp->below;
}
stackBottom = temp->item;
return true;
} // end bottom
我认为你必须做
StackItems *temp = top;
while (temp->below != NULL) {
temp = temp->below;
}
但是堆栈是 LIFO。 这不是:p
鉴于您使用链表作为底层存储,我只需在每次推送到空堆栈时设置底部指针,并在弹出最后一项时取消设置。
如果您使用数组(希望是动态的)作为底层存储,您只需索引第一项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.