我正在解决Webber的现代编程语言中的一些问题,我很难为IntList x实现一个append方法,其中该方法采用另一个IntList y并附加在x后面。这是代码:
public class IntList {
private ConsCell start;
public IntList cons (int h) {
return new IntList(new ConsCell(h, start));
}
public int length() {
int len = 0;
ConsCell cell = start;
while (cell != null) {
len++;
cell = cell.getTail();
}
return len;
}
public IntList append(IntList y) {
ConsCell x = start;
while (x.getTail() != nil) {
x = x.getTail;
}
x = y.start;
return new IntList(x);
}
}
继承人ConsCell的课程
public class ConsCell {
private int head;
private ConsCell tail;
public ConsCell(int h, ConsCell t) {
head = h;
tail = t;
}
public int getHead() {
return head;
}
public ConsCell getTail() {
return tail;
}
}
所以我在追加方法背后的思考过程是
不幸的是,该计划没有达到预期效果,我想知道是否有人可以给我一些见解?
答案 0 :(得分:0)
试试这个:
public IntList append(IntList y) {
ConsCell x = start;
while (x.getTail() != null) {
x = x.getTail();
}
x.tail = y.start;
return new IntList(start);
}
答案 1 :(得分:0)
append
方法应该是这样的
public IntList append(IntList y) {
ConsCell x = start;
while (x.getTail() != null) {
x = x.getTail();
}
x.setTail(y.getStart());
return this;
}
我认为你需要在你的类中添加setter方法,因为它们是私有的,需要setter才能访问它们。对变量设置setter和getter是个好习惯。
由于您已直接更改了ConsCell
方法中的append
个实例,因此返回自身或返回新的IntList
没有区别。在IntList
中进行修改将有效地修改另一个,因为它们指向同一个ConsCell
实例列表。
如果您确实需要一个独立于旧IntList
的新IntList
,则需要将ConsCell
中的每个元素复制到新的{{1}}。