【问题标题】:clone a LLL and increment each element in java [duplicate]克隆一个LLL并增加java中的每个元素[重复]
【发布时间】:2020-10-12 21:59:35
【问题描述】:

我正在尝试编写一个函数incrList(L, x),它递归地复制给定的线性链表L,并以一个常数值x 递增。当我在终端中编译时,我得到了IntList@6ff3c5b5,这是一个内存位置,而不是实际的列表。我只想更改函数 incrList 本身以提供正确的输出。

public class IntList {
    public int first;
    public IntList rest;

    public IntList(int f, IntList r) {
        first = f;
        rest = r;
    }
}

public class Lists1Exercises{

 
    public static IntList incrList(IntList L, int x) {
        if (L == null){
           return null;
        }else {
           IntList head = new IntList(L.first+x, null);
           head.rest = incrList(L.rest, x);
           return head;
        }
    }
public static void main(String[] args) {
        IntList L = new IntList(5, null);
        L.rest = new IntList(7, null);
        L.rest.rest = new IntList(9, null);


       
        System.out.println(incrList(L, 3));
    }
}

【问题讨论】:

标签: java


【解决方案1】:
public class IntList {
    public int first;
    public IntList rest;

    public IntList(int f, IntList r) {
        first = f;
        rest = r;
    }

    @override
    public String toString() {
        // or whatever you want to print
        return "First: " + first + " | Rest: " + rest;
    }
}

默认情况下,.toString() 返回一个字符串,该字符串由对象作为其实例的类的名称、at 符号字符“@”和对象哈希码的无符号十六进制表示形式组成。

但是您可以使用@override 更改它并返回您想要的任何内容(通常是有意义的内容)。

【讨论】:

    【解决方案2】:

    您需要重写 intlist 类中的 toString 方法或编写一个方法来从 intlist 转换为字符串。您正在返回一个对象,默认情况下它们打印为内存中的位置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多