-1

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

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() 如果我无法更改 insertSort();

*旁注:如果我的问题难以阅读或未正确提问,请致歉。我似乎有在这个网站上搞砸他们的诀窍。

4

1 回答 1

2

moveAfter()您的方法状态之前的注释:

如果指定的节点 current 为空,则将该节点插入到列表的头部。

由于insertionSort()使用head变量,我假设这是一个成员变量,您也可以moveAfter()按照规范所述使用它。

于 2013-01-22T21:48:55.540 回答