Construct a Doubly linked linked list from 2D Matrix
Last Updated :
23 Jan, 2023
Given a 2D matrix, the task is to convert it into a doubly-linked list with four pointers that are next, previous, up, and down, each node of this list should be connected to its next, previous, up, and down nodes.
Examples:
Input: 2D matrix
1 2 3
4 5 6
7 8 9
Output:

Approach: The main idea is to construct a new node for every element of the matrix and recursively create it’s up, down, previous and next nodes and change the pointer of previous and up pointers respectively.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
#define dim 3
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 << "\n" ;
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;
}
|
Java
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( "\n" );
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);
}
}
|
Python3
dim = 3
class Node:
def __init__( self , data):
self .data = data
self .prev = None
self .up = None
self .down = None
self . next = None
def createNode(data):
temp = Node(data);
return temp;
def constructDoublyListUtil(mtrx, i,
j, curr):
if (i > = dim or
j > = dim):
return None ;
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;
def constructDoublyList(mtrx):
return constructDoublyListUtil(mtrx,
0 , 0 ,
None );
def display(head):
rPtr = None
dPtr = head;
while (dPtr ! = None ):
rPtr = dPtr;
while (rPtr ! = None ):
print (rPtr.data,
end = ' ' )
rPtr = rPtr. next ;
print ()
dPtr = dPtr.down;
if __name__ = = "__main__" :
mtrx = [[ 1 , 2 , 3 ],
[ 4 , 5 , 6 ],
[ 7 , 8 , 9 ]]
list = constructDoublyList(mtrx);
display( list );
|
C#
using System;
class GFG{
static int dim= 3;
public class Node {
public int data;
public Node next, prev, up, 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 ) {
Console.Write(rPtr.data+ " " );
rPtr = rPtr.next;
}
Console.Write( "\n" );
dPtr = dPtr.down;
}
}
public static void Main()
{
int [,] mtrx = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
Node list = constructDoublyList(mtrx);
display(list);
}
}
|
Javascript
<script>
var dim = 3;
class Node
{
constructor()
{
this .data = 0;
this .next = null ;
this .prev = null ;
this .up = null ;
this .down = null ;
}
}
function createNode(data)
{
temp = new Node();
temp.data = data;
temp.next = null ;
temp.prev = null ;
temp.up = null ;
temp.down = null ;
return temp;
}
function constructDoublyListUtil(mtrx, i , j, curr)
{
if (i >= dim || j >= dim) {
return null ;
}
var 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;
}
function constructDoublyList(mtrx)
{
return constructDoublyListUtil(mtrx, 0, 0, null );
}
function display( head)
{
rPtr = null ;
dPtr = head;
while (dPtr != null ) {
rPtr = dPtr;
while (rPtr != null )
{
document.write(rPtr.data + " " );
rPtr = rPtr.next;
}
document.write( "<br/>" );
dPtr = dPtr.down;
}
}
var mtrx = [
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
];
var list = constructDoublyList(mtrx);
display(list);
</script>
|
Output:
1 2 3
4 5 6
7 8 9
Time Complexity: O(N*M)
Auxiliary Space: O(N*M) due to recursion
Method 2 – Iterative Approach
We will make use of dummy nodes to mark the start of up and prev pointers. Also in the above approach, we are creating so many extra nodes, here we will not be creating many extra nodes.
This approach performs better in the case of a large 2D Matrix, as it does not gets overhead recursion calls.
C++
#include<bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* left;
Node* right;
Node* up;
Node* down;
Node( int x) : data(x) , left(NULL) , right(NULL) , up(NULL) , down(NULL) {}
};
void print(Node* head) {
Node* downptr = head;
Node* rightptr;
while (downptr) {
rightptr = downptr;
while (rightptr) {
cout << (rightptr->data) << " " ;
rightptr = rightptr->right;
}
cout << "\n" ;
downptr = downptr->down;
}
}
int main() {
int mat[3][3] = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
int n = 3, m = 3;
Node* head_main = NULL;
Node* prev, *upper = new Node(-1);
for ( int i = 0; i < n; i++) {
Node* head_row;
Node *prev = new Node(-1);
for ( int j = 0; j < m; j++) {
Node* temp = new Node(mat[i][j]);
if (j == 0) head_row = temp;
if (i == 0 && j == 0) head_main = temp;
temp->left = prev;
prev->right = temp;
if (i == n - 1) temp->down = NULL;
if (!upper->right) {
upper->right = new Node(-1);
}
upper = upper->right;
temp->up = upper;
upper->down = temp;
prev = temp;
if (j == m - 1) prev->right = NULL;
}
upper = head_row->left;
}
print(head_main);
return 0;
}
|
Java
import java.util.*;
public class Main {
static class Node {
int data;
Node left;
Node right;
Node up;
Node down;
Node( int x)
{
data = x;
left = null ;
right = null ;
up = null ;
down = null ;
}
}
public static void print(Node head)
{
Node downptr = head;
Node rightptr;
while (downptr != null ) {
rightptr = downptr;
while (rightptr != null ) {
System.out.print(rightptr.data + " " );
rightptr = rightptr.right;
}
System.out.println();
downptr = downptr.down;
}
}
public static void main(String[] args)
{
int [][] mat
= { { 1 , 2 , 3 }, { 4 , 5 , 6 }, { 7 , 8 , 9 } };
int n = 3 , m = 3 ;
Node head_main
= null ;
Node prev, upper
= new Node(- 1 );
for ( int i = 0 ; i < n; i++) {
Node head_row
= new Node(- 1 );
prev = new Node(- 1 );
for ( int j = 0 ; j < m; j++) {
Node temp = new Node(mat[i][j]);
if (j == 0 )
head_row = temp;
if (i == 0 && j == 0 )
head_main = temp;
temp.left = prev;
prev.right = temp;
if (i == n - 1 )
temp.down = null ;
if (upper.right == null )
upper.right = new Node(- 1 );
upper = upper.right;
temp.up = upper;
upper.down = temp;
prev = temp;
if (j == m - 1 )
prev.right = null ;
}
upper = head_row.left;
}
print(head_main);
}
}
|
Python3
class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
self .up = None
self .down = None
def printList(head):
downptr = head
rightptr = None
while downptr ! = None :
rightptr = downptr
while rightptr ! = None :
print (rightptr.data, end = " " )
rightptr = rightptr.right
print ()
downptr = downptr.down
if __name__ = = "__main__" :
mat = [
[ 1 , 2 , 3 ],
[ 4 , 5 , 6 ],
[ 7 , 8 , 9 ]
]
n = 3
m = 3
head_main = None
prev = None
upper = Node( - 1 )
for i in range (n):
head_row = None
prev = Node( - 1 )
for j in range (m):
temp = Node(mat[i][j])
if j = = 0 :
head_row = temp
if i = = 0 and j = = 0 :
head_main = temp
temp.left = prev
prev.right = temp
if i = = n - 1 :
temp.down = None
if upper.right = = None :
upper.right = Node( - 1 )
upper = upper.right
temp.up = upper
upper.down = temp
prev = temp
if j = = m - 1 :
prev.right = None
upper = head_row.left
printList(head_main)
|
C#
using System;
class Program {
static void Main( string [] args)
{
int [, ] mat
= { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int n = 3, m = 3;
Node head_main
= null ;
Node prev, upper
= new Node(-1);
for ( int i = 0; i < n; i++) {
Node head_row
= new Node(-1);
prev = new Node(-1);
for ( int j = 0; j < m; j++) {
Node temp = new Node(mat[i, j]);
if (j == 0)
head_row = temp;
if (i == 0 && j == 0)
head_main = temp;
temp.left = prev;
prev.right = temp;
if (i == n - 1)
temp.down = null ;
if (upper.right == null )
upper.right = new Node(-1);
upper = upper.right;
temp.up = upper;
upper.down = temp;
prev = temp;
if (j == m - 1)
prev.right = null ;
}
upper = head_row.left;
}
print(head_main);
}
public static void print(Node head)
{
Node downptr = head;
Node rightptr;
while (downptr != null ) {
rightptr = downptr;
while (rightptr != null ) {
Console.Write(rightptr.data + " " );
rightptr = rightptr.right;
}
Console.WriteLine();
downptr = downptr.down;
}
}
}
class Node {
public int data;
public Node left;
public Node right;
public Node up;
public Node down;
public Node( int x)
{
data = x;
left = null ;
right = null ;
up = null ;
down = null ;
}
}
|
Javascript
<script>
class Node {
constructor(x)
{
this .data = x;
this .left = null ;
this .right = null ;
this .up = null ;
this .down = null ;
}
}
function print(head)
{
let downptr = head;
let rightptr;
while (downptr) {
rightptr = downptr;
while (rightptr) {
document.write(rightptr.data, " " );
rightptr = rightptr.right;
}
document.write( "</br>" );
downptr = downptr.down;
}
}
let mat = [
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
];
let n = 3, m = 3;
let head_main = null ;
let prev, upper = new Node(-1);
for (let i = 0; i < n; i++) {
let head_row;
let prev = new Node(-1);
for (let j = 0; j < m; j++) {
let temp = new Node(mat[i][j]);
if (j == 0) head_row = temp;
if (i == 0 && j == 0) head_main = temp;
temp.left = prev;
prev.right = temp;
if (i == n - 1) temp.down = null ;
if (!upper.right) {
upper.right = new Node(-1);
}
upper = upper.right;
temp.up = upper;
upper.down = temp;
prev = temp;
if (j == m - 1) prev.right = null ;
}
upper = head_row.left;
}
print(head_main)
</script>
|
Output:
1 2 3
4 5 6
7 8 9
Time Complexity: O(n*m) where n represents the number of rows, m represents the number of columns in our matrix.
Space Complexity: O(1) constant extra space.
Similar Reads
Construct a linked list from 2D matrix
Given a Matrix mat of n*n size, the task is to construct a 2D linked list representation of the given matrix. Example: Input : mat = [[1 2 3] [4 5 6] [7 8 9]]Output : Input : mat = [[23 28] [23 28]]Output : Table of Content [Expected Approach - 1] Recursive Approach - O(n^2) Time and O(n^2) Space[Ex
8 min read
Construct a linked list from 2D matrix (Iterative Approach)
Given a Matrix mat of n*n size, the task is to construct a 2D linked list representation of the given matrix. Example: Input : mat = [[1 2 3] [4 5 6] [7 8 9]]Output : Input : mat = [[23 28] [23 28]]Output : Approach: To Construct a linked list from 2D matrix iteratively follow the steps below: The i
9 min read
Create a Doubly Linked List from a Ternary Tree
Given a ternary tree, create a doubly linked list out of it. A ternary tree is just like a binary tree but instead of having two nodes, it has three nodes i.e. left, middle, and right. The doubly linked list should hold the following properties â The left pointer of the ternary tree should act as pr
12 min read
Search an element in a Doubly Linked List
Given a Doubly linked list(DLL) containing n nodes and an integer x, the task is to find the position of the integer x in the doubly linked list. If no such position found then print -1. Examples: Input: Linked List = 18 <-> 15 <-> 8 <-> 9 <-> 14, x = 8 Output: 3 Explanation:
7 min read
Convert a Binary Tree into Doubly Linked List in spiral fashion
Given a binary tree, convert it into a doubly linked list (DLL) where the nodes are arranged in a spiral order. The left pointer of the binary tree node should act as the previous node in the DLL, and the right pointer should act as the next node in the DLL. The solution should not allocate extra me
10 min read
Search an Element in Doubly Circular Linked List
Pre-requisite: Convert an Array to a Circular Doubly Linked List, Doubly Circular Linked ListGiven a doubly circular linked list. The task is to find the position of an element in the list. Image Representation: Algorithm: Declare a temp pointer, and initialize it to the head of the list.Iterate the
13 min read
XOR Linked List â A Memory Efficient Doubly Linked List | Set 2
In the previous post, we discussed how a Doubly Linked can be created using only one space for the address field with every node. In this post, we will discuss the implementation of a memory-efficient doubly linked list. We will mainly discuss the following two simple functions. A function to insert
10 min read
Convert given Binary Tree to Doubly Linked List in Linear time
Given a Binary Tree (BT), the task is to convert it to a Doubly Linked List (DLL) in place. The left and right pointers in nodes will be used as previous and next pointers respectively in converted DLL. The order of nodes in DLL must be the same as the order of the given Binary Tree. The first node
8 min read
Is two way linked list and doubly linked list same?
Yes, a two-way linked list and a doubly linked list are the same. Both terms refer to a type of linked list where each node contains a reference to the next node as well as the previous node in the sequence. The term âtwo-wayâ emphasizes the ability to move in both directions through the list, while
3 min read
Insert a linked list into another linked list
Given two linked lists, head1 and head2 of sizes m and n respectively. The task is to remove head1's nodes from the ath node to the bth node and insert head2 in their place. Examples: Input: a = 3, b = 4head1: 10 -> 11 -> 12 -> 13 -> 14 -> 15, head2: 100 -> 101 -> 102 -> 103O
10 min read