Construct a Doubly linked linked list from 2D Matrix | C ++ 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
#include <iostream> NEW_LINE using namespace std ; #define dim  3 NEW_LINE struct Node { int data ; Node * next ; Node * prev ; Node * up ; Node * down ; } ; 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 ; } Node * constructDoublyListUtil ( int mtrx [ ] [ dim ] , 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 ; } Node * constructDoublyList ( int mtrx [ ] [ dim ] ) { return constructDoublyListUtil ( mtrx , 0 , 0 , NULL ) ; } void display ( Node * head ) { Node * rPtr ; Node * dPtr = head ; while ( dPtr ) { rPtr = dPtr ; while ( rPtr ) { cout << rPtr -> data << " ▁ " ; rPtr = rPtr -> next ; } cout << " STRNEWLINE " ; dPtr = dPtr -> down ; } } int main ( ) { int mtrx [ dim ] [ dim ] = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; Node * list = constructDoublyList ( mtrx ) ; display ( list ) ; return 0 ; }