Reversing a singly linked list iteratively

后端 未结 7 1185
情话喂你
情话喂你 2021-01-01 08:17

Has to be O(n) and in-place (space complexity of 1). The code below does work, but is there a simpler or better way?

public void invert() {
    if (this.getH         


        
相关标签:
7条回答
  • 2021-01-01 08:47

    Edited to remove the extra comparison per iteration:

        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;
            }
        }
    
    0 讨论(0)
提交回复
热议问题