Reverse a Doubly Linked List | Set 4 ( Swapping Data ) | Java Program to Reverse a List using Data Swapping ; Insert a new node at the head of the list ; Function to reverse the list ; Traverse the list and set right pointer to end of list ; Swap data of left and right pointer and move them towards each other until they meet or cross each other ; Swap data of left and right pointer ; Advance left pointer ; Advance right pointer ; Driver code
class GFG { static class Node { int data ; Node prev , next ; } ; static Node newNode ( int val ) { Node temp = new Node ( ) ; temp . data = val ; temp . prev = temp . next = null ; return temp ; } static void printList ( Node head ) { while ( head . next != null ) { System . out . print ( head . data + " ▁ < - > ▁ " ) ; head = head . next ; } System . out . println ( head . data ) ; } static Node insert ( Node head , int val ) { Node temp = newNode ( val ) ; temp . next = head ; ( head ) . prev = temp ; ( head ) = temp ; return head ; } static Node reverseList ( Node head ) { Node left = head , right = head ; while ( right . next != null ) right = right . next ; while ( left != right && left . prev != right ) { int t = left . data ; left . data = right . data ; right . data = t ; left = left . next ; right = right . prev ; } return head ; } public static void main ( String args [ ] ) { Node head = newNode ( 5 ) ; head = insert ( head , 4 ) ; head = insert ( head , 3 ) ; head = insert ( head , 2 ) ; head = insert ( head , 1 ) ; printList ( head ) ; System . out . println ( " List ▁ After ▁ Reversing " ) ; head = reverseList ( head ) ; printList ( head ) ; } }