我的作业很简单,我不知道我做对了吗。我不确定像我那样在主函数中反向堆栈是否正确。有更好的方法吗?
#include <iostream>
#define STACK_MAX 5
using namespace std;
void push (int *stack, int &i, int number){
if (i<STACK_MAX){
stack[++i]=number;
}
}
int pop (int *stack, int &i){
int temp = 0;
if (i>0)
{
temp = stack[i--];
}
return temp;
}
int main (){
int stack[STACK_MAX], n = 0, i;
push (stack, n, 1);
push (stack, n, 2);
push (stack, n, 3);
push (stack, n, 9);
cout<<"Popped out: "<<pop (stack, n)<<endl;
push (stack, n, 4);
push (stack, n, 5);
cout <<"Stack:"<<endl;
while (i = pop(stack,n)){
cout << i << endl;
}
这部分困扰着我。我看到打印纸叠颠倒了,但是可以接受吗?
cout<<"Stack reversed: "<<endl;
for (int j = 1; j < STACK_MAX; j++){
stack[i] = stack[j];
cout<< stack[i] <<endl;
}
return 0;
}