O(n) でインプレース (スペースの複雑さ 1) である必要があります。以下のコードは機能しますが、もっと簡単で良い方法はありますか?
public void invert() {
if (this.getHead() == null)
return;
if (this.getHead().getNext() == null)
return;
//this method should reverse the order of this linked list in O(n) time
Node<E> prevNode = this.getHead().getNext();
Node<E> nextNode = this.getHead().getNext().getNext();
prevNode.setNext(this.getHead());
this.getHead().setNext(nextNode);
nextNode = nextNode.getNext();
while (this.getHead().getNext() != null)
{
this.getHead().getNext().setNext(prevNode);
prevNode = this.getHead().getNext();
this.getHead().setNext(nextNode);
if (nextNode != null)
nextNode = nextNode.getNext();
}
this.head = prevNode;
}