【发布时间】:2016-07-11 08:28:27
【问题描述】:
我想创建一个函数来获取堆栈(作为数组) 并让它返回堆栈,将堆栈中的第一个元素与最后一个元素交换 所以我将使用临时堆栈来存储数据 我会用 但是我怎么知道我什么时候会到达堆栈的末尾?
我已经将堆栈的实现写成一个数组 但我需要函数交换方面的帮助
void Swap(Stack x)
{
Stack tmp(100);
int top1 = x.pop;
for (int i = 0;; i++)
{
x.pop = tmp.push;
}
}
我知道它错了,但我不确定 任何帮助,将不胜感激 ,谢谢 编辑 我一开始是这样写函数的,发现不能带参数
void stack::Swap()
{
Stack tmp(100);
int top1 = this->pop;
for (int i = 0;; i++)
{
this->pop = tmp.push
}
};
此处编辑是来自答案的代码
Stack Swap(Stack x){
int mytop,mybottom;
mytop=x.pop();
int tmp[x.length-2],i=0;
while(!x.isEmpty()){
mybottom=x.pop();
tmp[i++]=mybottom;
}
Stack returnIt;
returnIt.push(mytop);
for(i=0;i<=x.length -3;i++){
returnIt.push(tmp[i]);
}
returnIt.push(mybottom);
return returnIt;
}
【问题讨论】: