在Java

时间:2017-10-25 07:17:53

标签: java

我正在解决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;
  }
}

所以我在追加方法背后的思考过程是

  1. 沿着列表向下直到结束(在这种情况下,当start.getTail为null时)
  2. 一旦到达列表的末尾,将新的IntList添加到x
  3. 的末尾
  4. 返回包含x和y
  5. 的新IntList

    不幸的是,该计划没有达到预期效果,我想知道是否有人可以给我一些见解?

2 个答案:

答案 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}}。