text: Reverse a doubly circular linked list | Java implementation to revesre a doubly circular linked list ; structure of a node of linked list ; function to create and return a new node ; Function to insert at the end ; If the list is empty , create a single node circular and doubly list ; Find last node / ; Start is going to be next of new_node ; Make new node previous of start ; Make last preivous of new node ; Make new node next of old last ; Uitlity function to revesre a doubly circular linked list ; Initialize a new head pointer ; get pointer to the the last node ; set ' curr ' to last node ; traverse list in backward direction ; insert ' curr ' at the end of the list starting with the ' new _ head ' pointer ; head pointer of the reversed list ; function to display a doubly circular list in forward and backward direction ; Driver code
code: class GFG { static class Node { int data ; Node next , prev ; } ; static Node getNode ( int data ) { Node newNode = new Node ( ) ; newNode . data = data ; return newNode ; } static Node insertEnd ( Node head , Node new_node ) { if ( head == null ) { new_node . next = new_node . prev = new_node ; head = new_node ; return head ; } Node last = ( head ) . prev ; new_node . next = head ; ( head ) . prev = new_node ; new_node . prev = last ; last . next = new_node ; return head ; } static Node reverse ( Node head ) { if ( head == null ) return null ; Node new_head = null ; Node last = head . prev ; Node curr = last , prev ; while ( curr . prev != last ) { prev = curr . prev ; new_head = insertEnd ( new_head , curr ) ; curr = prev ; } new_head = insertEnd ( new_head , curr ) ; return new_head ; } static void display ( Node head ) { if ( head == null ) return ; Node temp = head ; System . out . print ( " Forward ▁ direction : ▁ " ) ; while ( temp . next != head ) { System . out . print ( temp . data + " ▁ " ) ; temp = temp . next ; } System . out . print ( temp . data + " ▁ " ) ; Node last = head . prev ; temp = last ; System . out . print ( " Backward direction : "); while ( temp . prev != last ) { System . out . print ( temp . data + " ▁ " ) ; temp = temp . prev ; } System . out . print ( temp . data + " ▁ " ) ; } public static void main ( String args [ ] ) { Node head = null ; head = insertEnd ( head , getNode ( 1 ) ) ; head = insertEnd ( head , getNode ( 2 ) ) ; head = insertEnd ( head , getNode ( 3 ) ) ; head = insertEnd ( head , getNode ( 4 ) ) ; head = insertEnd ( head , getNode ( 5 ) ) ; System . out . print ( "Current list:NEW_LINE"); display ( head ) ; head = reverse ( head ) ; System . out . print ( " Reversed list : "); display ( head ) ; } }