【发布时间】:2023-01-30 19:51:22
【问题描述】:
我试图解决一个名为 push at bottom of stack 的问题。
我得到了递归逻辑,但问题是,我写了一个方法pushAtbottom,但main 方法无法识别该方法,我不明白为什么。错误是“无法解析 pushAtbottom”
import java.util.Stack;
public class pushatbottom {
public static void main(String[] args) {
Stack<Integer> s =new Stack<>();
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
s.pushAtbottom(6,s);
while(!s.isEmpty())
{
System.out.println(s.peek());
s.pop();
}
}
void pushAtbottom(int data,Stack<Integer> s)
{
if(s.isEmpty())
{
s.push(data);
}
int top=s.pop();
pushAtbottom(4,s);
s.push(top);
}
}
【问题讨论】:
-
pushAtbottom不是java.util.Stack类的方法,它是在您的pushatbottom类中定义的。使用pushAtbottom(6,s);,而不是s.pushAtbottom(6,s);,也使该方法static。另外你的递归调用是错误的,它应该是pushAtbottom(data, s);而不是pushAtbottom(4,s);。
标签: java data-structures methods compiler-errors stack