在Java中模拟链表
是否可以通过在类中嵌套类来模拟java中的链表?我已经尝试过实现,但是求和函数没有通过第一个类。无论给定什么整数,都会生成1:在Java中模拟链表,java,object,nested,Java,Object,Nested,是否可以通过在类中嵌套类来模拟java中的链表?我已经尝试过实现,但是求和函数没有通过第一个类。无论给定什么整数,都会生成1: public class Example { static class Item{ boolean b; double d; Item nextItem; Item (boolean b, double d, Item nextItem) { this.b = b;
public class Example {
static class Item{
boolean b;
double d;
Item nextItem;
Item (boolean b, double d, Item nextItem) {
this.b = b;
this.d = d;
this.nextItem = nextItem;
}
}
static double f(Item item) {
if(item != null)
return (item.b ? item.d : 0.0) + f(item.nextItem);
else
return 0.0;
}
static public void main(String args[]) {
int n = Integer.parseInt(args[0]);
Item firstItem = null;
firstItem = new Item((1%2!= 0), Math.sqrt(1), null);
if(n > 1){
Item nextItem = firstItem.nextItem;
for (int i = 2; i <= n; i++) {
nextItem = new Item((i%2!=0), Math.sqrt(i), null);
nextItem = nextItem.nextItem;
}
}
double s = f(firstItem);
System.out.println("sum = " + s);
}
}
公共类示例{
静态类项{
布尔b;
双d;
项目nextItem;
项目(布尔b,双d,项目nextItem){
这个.b=b;
这个。d=d;
this.nextItem=nextItem;
}
}
静态双f(项目){
如果(项!=null)
退货(b项?d项:0.0)+f(nextItem.nextItem);
其他的
返回0.0;
}
静态公共void main(字符串参数[]){
int n=Integer.parseInt(args[0]);
Item firstItem=null;
firstItem=新项((1%2!=0),Math.sqrt(1),null);
如果(n>1){
Item nextItem=firstItem.nextItem;
对于(int i=2;i当然,您可以使用嵌套类实现LinkedList。有很多方法可以实现它。这里有一个示例:
但问题是变量firstItem从未更改。您在此处赋值:firstItem=new Item((1%2!=0),Math.sqrt(1),null);
然后循环另一个始终为空的变量Item nextItem=firstItem.nextItem;
如果总是将构造函数的参数nextItem设置为null,请将其删除。for loop
的内容错误。应将nextItem
分配给firstItem.nextItem
。您必须添加更多逻辑来处理n>2