Construct a Doubly linked linked list from 2D Matrix | Java program to construct a Doubly linked linked list from 2D Matrix ; define dimension of matrix ; struct node of doubly linked list with four pointer next , prev , up , down ; function to create a new node ; function to construct the doubly linked list ; Create Node with value contain in matrix at index ( i , j ) ; Assign address of curr into the prev pointer of temp ; Assign address of curr into the up pointer of temp ; Recursive call for next pointer ; Recursive call for down pointer ; Return newly constructed node whose all four node connected at it 's appropriate position ; Function to construct the doubly linked list ; function call for construct the doubly linked list ; function for displaying doubly linked list data ; pointer to move right ; pointer to move down ; loop till node . down is not null ; loop till node . right is not null ; driver code ; initialise matrix
import java . util . * ; class GFG { static int dim = 3 ; static class Node { int data ; Node next ; Node prev ; Node up ; Node down ; } ; static Node createNode ( int data ) { Node temp = new Node ( ) ; temp . data = data ; temp . next = null ; temp . prev = null ; temp . up = null ; temp . down = null ; return temp ; } static Node constructDoublyListUtil ( int mtrx [ ] [ ] , int i , int j , Node curr ) { if ( i >= dim j >= dim ) { return null ; } Node temp = createNode ( mtrx [ i ] [ j ] ) ; temp . prev = curr ; temp . up = curr ; temp . next = constructDoublyListUtil ( mtrx , i , j + 1 , temp ) ; temp . down = constructDoublyListUtil ( mtrx , i + 1 , j , temp ) ; return temp ; } static Node constructDoublyList ( int mtrx [ ] [ ] ) { return constructDoublyListUtil ( mtrx , 0 , 0 , null ) ; } static void display ( Node head ) { Node rPtr ; Node dPtr = head ; while ( dPtr != null ) { rPtr = dPtr ; while ( rPtr != null ) { System . out . print ( rPtr . data + " ▁ " ) ; rPtr = rPtr . next ; } System . out . print ( "NEW_LINE"); dPtr = dPtr . down ; } } public static void main ( String args [ ] ) { int mtrx [ ] [ ] = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; Node list = constructDoublyList ( mtrx ) ; display ( list ) ; } }