Iteratively Reverse a linked list using only 2 pointers ( An Interesting Method ) | Java program to reverse a linked list using two pointers . ; Link list node ; Function to reverse the linked list using 2 pointers ; At last prev points to new head ; This expression evaluates from left to right current . next = prev , changes the link fron next to prev node prev = current , moves prev to current node for next reversal of node This example of list will clear it more 1.2 . 3.4 initially prev = 1 , current = 2 Final expression will be current = 1 ^ 2 ^ 3 ^ 2 ^ 1 , as we know that bitwise XOR of two same numbers will always be 0 i . e ; 1 ^ 1 = 2 ^ 2 = 0 After the evaluation of expression current = 3 that means it has been moved by one node from its previous position ; Function to push a node ; Allocate node ; Put in the data ; Link the old list off the new node ; Move the head to point to the new node ; Function to print linked list ; Driver code
import java . util . * ; class Main { static class Node { int data ; Node next ; } ; static Node head_ref = null ; static void reverse ( ) { Node prev = null ; Node current = head_ref ; while ( current != null ) { Node next = current . next ; current . next = prev ; prev = current ; current = next ; } head_ref = prev ; } static void push ( int new_data ) { Node new_node = new Node ( ) ; new_node . data = new_data ; new_node . next = ( head_ref ) ; ( head_ref ) = new_node ; } static void printList ( ) { Node temp = head_ref ; while ( temp != null ) { System . out . print ( temp . data + " ▁ " ) ; temp = temp . next ; } } public static void main ( String [ ] args ) { push ( 20 ) ; push ( 4 ) ; push ( 15 ) ; push ( 85 ) ; System . out . print ( "Given linked listNEW_LINE"); printList ( ) ; reverse ( ) ; System . out . print ( " Reversed Linked list "); printList ( ) ; } }