此代码是否将null传递给moveAfter()以及如何处理它

时间:2013-01-22 21:42:44

标签: java linked-list nodes

所以我得到了这个代码,据我所知,我不允许改变:

public void insertionSort () {
    if (head == tail) {
        // empty list is sorted
        return;
    }
    Node nextNode = head.next; // start inserting second node
    while (nextNode != tail) {
        // set insertNode to node to be inserted in this iteration
        Node insertNode = nextNode; 
        // set nextNode to node to be inserted in next iteration
        nextNode = nextNode.next;  

        // find position where insertNode has to be inserted
        Node current = insertNode.prev;
        while (current != null && insertNode.value.compareTo(current.value) < 0) {
            current = current.prev;
        }

        // insert insertNode after current
        insertNode.moveAfter(current);
    }
}

我对链表不是很熟悉,但是我可以判断第二次while循环是否在第一次迭代时运行,然后这段代码将null传递给moveAfter()到目前为止,moveAfter()我有:

 /**
     * Inserts this node after the specified node. If this and the specified node 
     * refer to the same node in the list, the list remains unchanged. If the 
     * specified node current is null, then this node is inserted at the head of 
     * the list.
     *
     * Precondition: this Node and the specified node are two nodes of this list
     *               this node and the specified node are not equal to the tail
     * 
     * @param node - the node in this list after which this node is inserted
     */
    public void moveAfter (Node node) {
        if(this.prev == null && node.next == null){
            throw new NoSuchElementException();
        }
        if(node.prev == null && node.next==null){
            throw new NoSuchElementException();
        }
        if(this == tail){
            throw new NoSuchElementException();
        }
        if(node == tail){
            throw new NoSuchElementException();
        }

          this.prev.next = this.next;
          this.next = node.next;
          node.next = this;                            
          this.prev = node;
    }
}  

如果我是正确的,insertSort()将null传递给moveAfter(),如果我无法更改insertionSort(),我怎么能纠正这个并将“current”重置为原始值;

*附注:如果我的问题难以阅读或未正确询问,请致歉。我似乎很擅长把它们搞砸在这个网站上。

1 个答案:

答案 0 :(得分:2)

moveAfter()方法状态之前的评论:

  

如果指定的节点当前为空,则此节点将插入列表的开头。

由于insertionSort()使用head变量,我认为这是一个成员变量,您也可以在moveAfter()中使用该变量作为规范说明。