必须是 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;
}