0

我知道这个问题之前被问过几次,但其他主题似乎都没有讨论我正在尝试做的事情。

public void add(int Value) {
      DListNode previous = null;
      DListNode current = first;

      while ((Integer)current.getValue() < Value) {
          previous = current;           //move previous up to current
           current = current.getNext(); //advance current one node ahead

           if (current == null) {  //if current is the very last node in the list
               break;
           }
      }

      if (previous == null) { //if the previous object is null, the value should be inserted at the front
          first = new DListNode(Value, first, null);
      }
      else { //if not, the value should be inserted between current and previous
          previous.setNext(new DListNode(Value, current, previous));

      }

      getLast();  //updates the last field (Not important)

  }

DListNode 是一个包含整数变量、Next DListNode 和前一个 DListNode(以及标准的 getter 和 setter 方法)的类。它使用参数 DListNode(value, next node, previous node) 进行初始化。存储的值是 Object 类型。

我想要做的是在当前和上一个之间插入一个新节点。新节点应设置为previous的下一个节点,current设置为新节点的下一个节点,previous设置为新节点的前一个节点,新节点设置为current的前一个节点。仅当该值大于第一个节点中包含的值时才会发生这种情况。但是,节点只会向前链接,我不知道为什么。

如有必要,我可以发布整个课程,任何帮助或想法将不胜感激。

编辑:我在 Archer 的帮助下想通了。如果有人想知道,这是我的最终方法(我必须添加另一个 if/else 语句来处理 nullPointerErrors)。

public void add(int Value) {
      DListNode previous = null;
      DListNode current = first;

      while ((Integer)current.getValue() < Value) {
          previous = current;           //move previous up to current
           current = current.getNext(); //advance current one node ahead

           if (current == null) {  //if current is the very last node in the list
               break;
           }
      }

      if (previous == null) { //if the previous object is null, the value should be inserted at the front
          DListNode insert = new DListNode(Value, current, previous);
          current.setPrevious(insert);
          first = insert;
      }
      else { //if not, the value should be inserted between current and previous
          if (current == null) {
          DListNode insert = new DListNode(Value, current, previous);
          previous.setNext(insert);
          }
          else {
             DListNode insert = new DListNode(Value, current, previous);
             current.setPrevious(insert);
              previous.setNext(insert);
          }

      }

      getLast();  //updates the last field

  }
4

1 回答 1

2

这几行有问题:

first = new DListNode(Value, first, null);

previous.setNext(new DListNode(Value, current, previous));

您只是添加节点而不更新附近节点的引用。

第一行应如下所示:

first = new DListNode(Value, first, null);
first.getNext().setPrevious(first)

第二行应如下所示:

previous.setNext(new DListNode(Value, current, previous));
current.setPrevious(previous.getNext())

类似的东西。

于 2013-01-14T06:59:13.350 回答