实现我自己的有序双链表(Java)

时间:2013-01-14 06:35:41

标签: java

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

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(值,下一个节点,上一个节点)初始化。存储的值是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

  }

1 个答案:

答案 0 :(得分: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())

类似的东西。