2

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]);
    }
}
Zabuzard
  • 25,064
  • 8
  • 58
  • 82
Khanh Tiet
  • 21
  • 2
  • 2
    In your code, `array` is not initialized, it is `null` . – Arnaud Oct 17 '17 at 12:57
  • But I try to fix by int[] array ={0}; – Khanh Tiet Oct 17 '17 at 12:58
  • And it's not work. – Khanh Tiet Oct 17 '17 at 12:58
  • 2
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – M. le Rutte Oct 17 '17 at 12:58
  • 2
    you need int[] array = new int[ size of the list ]; – mlecz Oct 17 '17 at 12:59
  • 1
    Also, `for (int j = i....` will give you an index exception. You want `j = i - 1`. – 001 Oct 17 '17 at 13:02
  • For future questions it would be best if you also **post the complete error message** here. Especially the `StackTrace` contains information which is helpful for debugging. It exactly tells us at which line the `NPE` occurred and which events triggered that, then we don't need to find the source first. – Zabuzard Oct 17 '17 at 13:40
  • @KhanhTiet If an user answered your question please also accept his answer ([Accepting Answers: How does it work?](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)). If not then please specify what remains unanswered, this is a crucial part of StackOverflow, thank you very much. – Zabuzard Nov 14 '17 at 10:23

2 Answers2

2

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.

Zabuzard
  • 25,064
  • 8
  • 58
  • 82
1

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);
    }
}
Maurice Perry
  • 9,261
  • 2
  • 12
  • 24
  • Simple yes. But depending on the size of the list that may easily end up in `StackOverflowError`. Just as a note for OP. – Zabuzard Oct 17 '17 at 13:13
  • so I shouldn't use this code if the size of the list is big, right @Zabuza – Khanh Tiet Oct 17 '17 at 13:21
  • That is correct. This recursion calls `size`-often the method before it starts to finish one of them. Every method-call costs some space on the **stack** (you need to remember variables, pointers, everything from all other method calls). At some point the limit is reached and you'll get a `StackOverflowError`: [What is a StackOverflowError?](https://stackoverflow.com/questions/214741/what-is-a-stackoverflowerror) and [How many recursive calls before StackOverflowError?](https://stackoverflow.com/questions/17285115/how-many-recursive-calls-before-stackoverflowerror) – Zabuzard Oct 17 '17 at 13:32