我正在写一段代码从Stack中弹出并繁殖。我知道我可以打印我的pop'd整数,但是如果我弹出另一个整数,我如何跟踪一个pop'd整数?
我正在尝试使用基本计数器编写一个for循环来弹出顶部整数,将其保存到变量,然后将该变量乘以下一个弹出的整数。
static LStack<Integer> stack = new LStack<Integer>();
static public void main (String[] args)
{
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
for(int i = stack.length(); i <= 0; i++) {
stack.pop();
}
}
您可能会发现使用while
循环更容易/更清楚:
int result = stack.pop();
while (!stack.empty()) {
result *= stack.pop();
}
如果你必须使用for
循环:
int result;
for (result = stack.pop(); !stack.empty();)
result *= stack.pop();
}
无论如何,关键是用堆栈顶部的值初始化最终结果,然后将它乘以从堆栈弹出的每个元素。
static LStack<Integer> stack = new LStack<Integer>();
/ * fact()函数* /
public static void main(String[] args) {
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
System.out.println(calc(stack.pop()));
}
public static long calc(long n) {
if (n <= 1)
return 1;
else
return n * calc(n - 1);
}
}
这是我最终使用的,从另一个帖子实现计算器,它似乎工作,并允许我推动额外的整数。谢谢大家的时间!