• + 2 comments

    It works like this: in a double-linked list that has been reversed, the values of each node's 'next' and 'prev' fields are swapped (the nodes before and after each node swap positions). The code above does just that; starting at the head of the list it works through the list swapping 'next' and 'prev' values.

    As for why you got a NullPointer exception, a pointer without a target has a value of NULL, thus a loop that moves from node to node ends when its "iterator" variable is assigned null (that's why newHead's value is updated before temp's value). In short, your print statement tried to get a field value from said null.

    • + 6 comments

      Here's a four line solution using recursion.

          static DoublyLinkedListNode reverse(DoublyLinkedListNode curr) {
          DoublyLinkedListNode temp = curr.next;
          curr.next = curr.prev;
          curr.prev = temp;
          return temp == null ? curr : reverse(temp);
      }
      
      • + 1 comment

        Good Logic! It helped alot! Thank You!

      • + 0 comments

        beautiful!

      • + 0 comments

        Neat solution. Loved it !

      • + 0 comments

        Brilliant

      • + 0 comments

        hey, can you explain 3,4 line. i don't understand, why you use this.

      • + 0 comments

        you solution is the best

    • + 0 comments

      here is problem solution in java python c++ c and javascript programming.

      HackerRank Reverse a doubly linked list solution