编程语言
首页 > 编程语言> > java – 迭代地反转单链表

java – 迭代地反转单链表

作者:互联网

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

解决方法:

编辑以删除每次迭代的额外比较:

    public void invert() {
        Node<E> prev = null, next = null;;
        if (head == null) return;
        while (true) {
            next = head.getNext();
            head.setNext(prev);
            prev = head;
            if (next == null) return;
            head = next;
        }
    }

标签:java,linked-list,singly-linked-list
来源: https://codeday.me/bug/20191005/1856229.html