Given a linked list, the task is to write a program in Java that reverses the linked list without manipulating its pointers, i.e., the reversal should happen just by changing the data values and not the links.
Input: Original linked list 1->2->3->4->5->null Output: Linked list after reversal 5->4->3->2->1->null Input: Original linked list 5->14->20->8->null Output: Linked list after reversal 8->20->14->5->null Input: Original linked list 80->null Output: Linked list after reversal 80->null
For reversal, no manipulation is done in the links that connect the node of the linked list. Only the data values are changed. To understand this more clearly, take a look at the following diagram.
The numbers in red color represent the addresses of nodes. It is to be noticed that even after the reversal, the links remained the same, i.e., before reversing, the node at address 100 was connected to the node at address 200, which in turn was connected to the node at address 300 and so on, and these connections have remained the same after the reversal as well.
- Variables ‘l’ and ‘r’ are initialized as 0 and size-1 respectively, denoting the index of first and last node.
- In a loop, the nodes at index ‘l’ and ‘r’ are obtained and the corresponding data values are swapped. The loop works by incrementing ‘l’ and decrementing ‘r’.
- For getting the node at a particular index, a private method ‘fetchNode’ is defined.
Below is the implementation of the above approach:
Linked List Before Reversal: 1 2 3 4 5 Linked List After Reversal: 5 4 3 2 1
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.