Reverse a Linked List

Problem

Build a singly linked list from the array. Reverse the list by changing the links (do not copy the values into a new array). Print the values of the reversed list.

Constraints

  • 1 <= n <= 10^5

Examples

Input

5
1 2 3 4 5

Output

5 4 3 2 1

Solutions

Best approachTime O(n)Space O(1) extra

We walk through the list once and turn every link to point backwards. Three pointers are enough, so no extra memory is needed beyond the nodes.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Process the list.
 * Input   : n, then n integers.
 * Output  : The reversed list.
 * Approach: Turn every link around.
 * Time    : O(n)
 * Space   : O(1) extra
 * Java    : 8 or newer.
 */
import java.util.Scanner;
import java.util.Arrays;
import java.util.stream.Collectors;

public class Main {
        // Step 1: A node holds one value and a link to the next node. The last node links to null.
        static class Node {
            int value;
            Node next;

            Node(int value) {
                this.value = value;
            }
        }

    // This method solves the task. It receives the input and returns the answer.
    static int[] solve(int[] a) {
        // Step 2: Build the list. head is the first node, tail is the last node.
        Node head = null;
        Node tail = null;
        for (int value : a) {
            Node node = new Node(value);
            if (head == null) {
                head = node;
            } else {
                tail.next = node;
            }
            tail = node;
        }

        // Step 3: Reverse. previous is the already reversed part. current is the node we handle now.
        Node previous = null;
        Node current = head;
        while (current != null) {
            // Step 4: Remember the next node, turn the link back, and move both pointers one step.
            Node next = current.next;
            current.next = previous;
            previous = current;
            current = next;
        }

        // Step 5: previous is the new head. Copy the values to an array for printing.
        int[] result = new int[a.length];
        int index = 0;
        for (Node node = previous; node != null; node = node.next) {
            result[index++] = node.value;
        }
        return result;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int size = scanner.nextInt();
        int[] a = new int[size];
        for (int i = 0; i < size; i++) {
            a[i] = scanner.nextInt();
        }
        System.out.println(Arrays.stream(solve(a)).mapToObj(String::valueOf).collect(Collectors.joining(" ")));
    }
}
Hints (1)
  1. What must you save before you change current.next?