Khanh Tiet
Khanh Tiet

Reputation: 21

Print reverse in linkedlist

I want to write function Print Reverse of LinkedList in Java. I write like this but it doesn't work. Compiler warn that NullPointerException.

void ReversePrint(Node head) {
    int[] array = null;
    int i = 0;
    Node tmp;
    for (tmp = head; tmp != null; tmp = tmp.next) {
        array[i] = tmp.data;
        i++;
    }
    for(int j = i; j >= 0; j--){
        System.out.println(array[j]);
    }
}

Upvotes: 2

Views: 456

Answers (2)

Zabuzard
Zabuzard

Reputation: 25903

You get the NullPointerException because the variable array is null:

int[] array = null;

You need to initialize it first with a value before you are using it here:

array[i] = tmp.data;

For example with a statement like this:

int[] array = new int[size];

Where size should probably be the size of your LinkedList. If you, for whatever reason, don't know the size, you can use the class ArrayList which realizes arrays with dynamic size (it guesses a size and if your exceeding it, it will re-allocate a bigger array and copy everything over and so on).

Here's a version using said ArrayList:

// Method names should start with a lower-case letter
void reversePrint(Node head) {
    // Initialize an empty ArrayList
    ArrayList<Integer> dataList = new ArrayList<>();
    int i = 0;
    Node tmp;
    for (tmp = head; tmp != null; tmp = tmp.next) {
        // Set the element at position i of the ArrayList
        dataList.set(i, tmp.data);
        i++;
    }

    // See next comment
    i--;

    for(int j = i; j >= 0; j--){
        // Get the element at position j of ArrayList and print it
        System.out.println(dataList.get(j));
    }
}

Note that you will also encounter an IndexOutOfBoundException since your i is 1 to big when reaching the print-loop. This is because you increased it also in the last iteration of your first loop:

// Suppose last iteration, i is (list.size() - 1) then
for (tmp = head; tmp != null; tmp = tmp.next) {
    array[i] = tmp.data;
    // i is now list.size()
    i++;
}

You need one i-- between the loops or int j = i - 1 in your loop initialization.


If you are realizing a doubly-linked list instead of only a single-linked list then note that you do not need to story values in an array first. You then can directly print the values by starting at tail and following tmp.prev pointers.

Upvotes: 2

Maurice Perry
Maurice Perry

Reputation: 9650

The simplest way to do this is with a recursive method:

void ReversePrint(Node node) {
    if (node != null) {
        ReversePrint(node.next);
        System.out.println(node.data);
    }
}

Upvotes: 1

Related Questions