Reversing a singly linked list iteratively

后端 未结 7 1183
情话喂你
情话喂你 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:43

    Using a self-contained implementation, i.e. the List is represented by the head Node:

    public class Node
    {
        Node next;
        E value;
    
        public Node(E value, Node next)
        {
            this.value = value;
            this.next = next;
        }
    
        public Node reverse()
        {
            Node head = null;
            Node current = this;
            while (current != null) {
                Node save = current;
                current = current.next;
                save.next = head;
                head = save;
            }
            return head;
        }
    }
    

提交回复
热议问题