如何使用堆栈计算 n 的阶乘

-2 c++ stack factorial

我需要使用堆栈计算 n 的阶乘,并且我编写的代码不返回任何结果。我也不知道 pop stack 真正做了什么(它的第二个参数是什么)所以我只是在那里使用了一个随机值。我使用int **x;是因为我不知道该放什么pop(&mystack,*x);

#include <iostream>
using namespace std;
int n;
int aux;
int aux1;
int aux2;
int **x;
typedef struct {
    int content[100];
    int top;
} stack;
stack mystack;

int push(stack *somestack,int somevalue)
{
    if (somestack->top+1>=100)
        return 1;
    (*somestack).top++;
    (*somestack).content[(*somestack).top]=somevalue;
    return 0;
}

int pop(stack *somestack, int *oldvalue)
{
    if((*somestack).top==0)
    {
        return 1;
    }
    *oldvalue=(*somestack).content[(*somestack).top];
    return 0;
}

int main()
{
    cout<<"n=";
    cin>>n;
    push(&mystack,n);
    int direction=1;
    while(mystack.top>=1)
    {
        if((direction==1)&&(mystack.content[mystack.top]>1))
        {
            aux=mystack.content[mystack.top];
            push(&mystack,aux-1);
        }
        else
        {
            if(mystack.content[mystack.top]==1)
            {
                direction=0;
            }
            else
            {
                if(aux1<n)
                {
                    aux1=mystack.content[mystack.top];
                    aux2=aux1*(aux1+1);
                    pop(&mystack,*x);
                    mystack.content[mystack.top]=aux2;
                }
            }
        }
    }
    cout<<endl<<mystack.content[0];
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Atu*_*uos 5

堆栈具有推送和弹出操作。Push 将一个新项目添加到堆栈顶部,pop 从堆栈顶部删除该项目并返回它。阶乘的一些伪代码:

int factorial(int n) {
    Stack<int> stack;
    stack.push(1);

    for(int i=1; i<=n; ++i) {
       stack.push(stack.pop()*i);
    }
    return stack.pop();
}
Run Code Online (Sandbox Code Playgroud)