The Wayback Machine - https://web.archive.org/web/20240903154919/https://www.geeksforgeeks.org/construct-a-doubly-linked-linked-list-from-2d-matrix/
Open In App

Construct a Doubly linked linked list from 2D Matrix

Last Updated : 23 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Easy
67.79%
13.3K

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++




// C++ program to construct a Doubly
// linked linked list from 2D Matrix
 
#include <iostream>
using namespace std;
 
// define dimension of matrix
#define dim 3
 
// struct node of doubly linked
// list with four pointer
// next, prev, up, down
struct Node {
    int data;
    Node* next;
    Node* prev;
    Node* up;
    Node* down;
};
 
// function to create a new node
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;
}
 
// function to construct the
// doubly linked list
Node* constructDoublyListUtil(
    int mtrx[][dim],
    int i, int j,
    Node* curr)
{
 
    if (i >= dim || j >= dim) {
        return NULL;
    }
 
    // Create Node with value contain
    // in matrix at index (i, j)
    Node* temp = createNode(mtrx[i][j]);
 
    // Assign address of curr into
    // the prev pointer of temp
    temp->prev = curr;
 
    // Assign address of curr into
    // the up pointer of temp
    temp->up = curr;
 
    // Recursive call for next pointer
    temp->next
        = constructDoublyListUtil(
            mtrx, i, j + 1, temp);
 
    // Recursive call for down pointer
    temp->down
        = constructDoublyListUtil(
            mtrx, i + 1, j, temp);
 
    // Return newly constructed node
    // whose all four node connected
    // at it's appropriate position
    return temp;
}
 
// Function to construct the doubly linked list
Node* constructDoublyList(int mtrx[][dim])
{
    // function call for construct
    // the doubly linked list
    return constructDoublyListUtil(
        mtrx, 0, 0, NULL);
}
 
// function for displaying
// doubly linked list data
void display(Node* head)
{
    // pointer to move right
    Node* rPtr;
 
    // pointer to move down
    Node* dPtr = head;
 
    // loop till node->down is not NULL
    while (dPtr) {
 
        rPtr = dPtr;
 
        // loop till node->right is not NULL
        while (rPtr) {
            cout << rPtr->data << " ";
            rPtr = rPtr->next;
        }
 
        cout << "\n";
        dPtr = dPtr->down;
    }
}
 
// driver code
int main()
{
 
    // initialise matrix
    int mtrx[dim][dim] = {
        { 1, 2, 3 },
        { 4, 5, 6 },
        { 7, 8, 9 }
    };
 
    Node* list = constructDoublyList(mtrx);
 
    display(list);
 
    return 0;
}


Java




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


Python3




# Python3 program to construct
# a Doubly linked linked list
# from 2D Matrix
  
# define dimension of matrix
dim = 3
  
# struct node of doubly linked
# list with four pointer
# next, prev, up, down
class Node:
     
    def __init__(self, data):
       
        self.data = data
        self.prev = None
        self.up = None
        self.down = None
        self.next = None       
         
# function to create a
# new node
def createNode(data):
 
    temp = Node(data);   
    return temp;
  
# function to construct the
# doubly linked list
def constructDoublyListUtil(mtrx, i,
                            j, curr):
  
    if (i >= dim or
        j >= dim):
        return None;
      
    # Create Node with value
    # contain in matrix at
    # index (i, j)
    temp = createNode(mtrx[i][j]);
  
    # Assign address of curr into
    # the prev pointer of temp
    temp.prev = curr;
  
    # Assign address of curr into
    # the up pointer of temp
    temp.up = curr;
  
    # Recursive call for next
    # pointer
    temp.next= constructDoublyListUtil(mtrx, i,
                                       j + 1,
                                       temp);
  
    # Recursive call for down pointer
    temp.down= constructDoublyListUtil(mtrx,
                                       i + 1,
                                       j, temp);
  
    # Return newly constructed node
    # whose all four node connected
    # at it's appropriate position
    return temp;
 
# Function to construct the
# doubly linked list
def constructDoublyList(mtrx):
 
    # function call for construct
    # the doubly linked list
    return constructDoublyListUtil(mtrx,
                                   0, 0,
                                   None);
   
# function for displaying
# doubly linked list data
def display(head):
 
    # pointer to move right
    rPtr = None
  
    # pointer to move down
    dPtr = head;
  
    # loop till node->down
    # is not NULL
    while (dPtr != None):
  
        rPtr = dPtr;
  
        # loop till node->right
        # is not NULL
        while (rPtr != None):
            print(rPtr.data,
                  end = ' ')
            rPtr = rPtr.next;
         
        print()
        dPtr = dPtr.down;
     
# Driver code
if __name__=="__main__":
     
    # initialise matrix
    mtrx =[[1, 2, 3],
           [4, 5, 6],
           [7, 8, 9]]
  
    list = constructDoublyList(mtrx);
    display(list);
 
# This code is contributed by Rutvik_56


C#




// C# program to construct a Doubly
// linked linked list from 2D Matrix
using System;
 
class GFG{
    // define dimension of matrix
    static int dim= 3;
     
    // struct node of doubly linked
    // list with four pointer
    // next, prev, up, down
    public class Node {
        public int data;
        public Node next, prev, up, down;
    };
     
    // function to create a new node
    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;
    }
     
    // function to construct the
    // doubly linked list
    static Node constructDoublyListUtil(int[,] mtrx,int i, int j,Node curr)
    {
     
        if (i >= dim || j >= dim) {
            return null;
        }
     
        // Create Node with value contain
        // in matrix at index (i, j)
        Node temp = createNode(mtrx[i,j]);
     
        // Assign address of curr into
        // the prev pointer of temp
        temp.prev = curr;
     
        // Assign address of curr into
        // the up pointer of temp
        temp.up = curr;
     
        // Recursive call for next pointer
        temp.next
            = constructDoublyListUtil(mtrx, i, j + 1, temp);
     
        // Recursive call for down pointer
        temp.down= constructDoublyListUtil(mtrx, i + 1, j, temp);
     
        // Return newly constructed node
        // whose all four node connected
        // at it's appropriate position
        return temp;
    }
     
    // Function to construct the doubly linked list
    static Node constructDoublyList(int[,] mtrx)
    {
        // function call for construct
        // the doubly linked list
        return constructDoublyListUtil(mtrx, 0, 0, null);
    }
     
    // function for displaying
    // doubly linked list data
    static void display(Node head)
    {
        // pointer to move right
        Node rPtr;
     
        // pointer to move down
        Node dPtr = head;
     
        // loop till node.down is not null
        while (dPtr != null) {
     
            rPtr = dPtr;
     
            // loop till node.right is not null
            while (rPtr!=null) {
                Console.Write(rPtr.data+" ");
                rPtr = rPtr.next;
            }
     
            Console.Write("\n");
            dPtr = dPtr.down;
        }
    }
     
    // driver code
    public static void Main()
    {
     
        // initialise matrix
        int[,] mtrx = {
            { 1, 2, 3 },
            { 4, 5, 6 },
            { 7, 8, 9 }
        };
     
        Node list = constructDoublyList(mtrx);
     
        display(list);
     
    }
}
 
// This code is contributed by AbhiThakur


Javascript




<script>
// javascript program to construct a Doubly
// linked linked list from 2D Matrix
   // define dimension of matrix
    var dim = 3;
     
    // struct node of doubly linked
    // list with four pointer
    // next, prev, up, down
    class Node
    {
        constructor()
        {
     
        this.data = 0;
        this.next = null;
        this.prev = null;
        this.up = null;
        this.down = null;
        }
    }
     
    // function to create a new node
   function createNode(data)
    {
         temp = new Node();
        temp.data = data;
        temp.next = null;
        temp.prev = null;
        temp.up = null;
        temp.down = null;
        return temp;
    }
     
    // function to construct the
    // doubly linked list
    function constructDoublyListUtil(mtrx, i , j, curr)
    {
     
        if (i >= dim || j >= dim) {
            return null;
        }
     
        // Create Node with value contain
        // in matrix at index (i, j)
        var temp = createNode(mtrx[i][j]);
     
        // Assign address of curr into
        // the prev pointer of temp
        temp.prev = curr;
     
        // Assign address of curr into
        // the up pointer of temp
        temp.up = curr;
     
        // Recursive call for next pointer
        temp.next
            = constructDoublyListUtil(mtrx, i, j + 1, temp);
     
        // Recursive call for down pointer
        temp.down= constructDoublyListUtil(mtrx, i + 1, j, temp);
     
        // Return newly constructed node
        // whose all four node connected
        // at it's appropriate position
        return temp;
    }
     
    // Function to construct the doubly linked list
    function constructDoublyList(mtrx)
    {
     
        // function call for construct
        // the doubly linked list
        return constructDoublyListUtil(mtrx, 0, 0, null);
    }
     
    // function for displaying
    // doubly linked list data
    function display( head)
    {
     
        // pointer to move right
         rPtr = null;
     
        // pointer to move down
         dPtr = head;
     
        // loop till node.down is not null
        while (dPtr != null) {
     
            rPtr = dPtr;
     
            // loop till node.right is not null
            while (rPtr != null)
            {
                document.write(rPtr.data + " ");
                rPtr = rPtr.next;
            }
     
            document.write("<br/>");
            dPtr = dPtr.down;
        }
    }
     
    // driver code
     
        // initialise matrix
        var mtrx = [
            [ 1, 2, 3 ],
            [ 4, 5, 6 ],
            [ 7, 8, 9 ]
        ];
     
        var list = constructDoublyList(mtrx);
        display(list);
     
// This code is contributed by todaysgaurav
</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;   // To hold the value of matrix
 
    // 4 pointers for left, right, up, down for markings.
    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) {
    // Require 2 pointers, downptr and rightptr, for rows and columns.
    Node* downptr = head;
    Node* rightptr;
    while (downptr) {
        rightptr = downptr;
        while (rightptr) {
            cout << (rightptr->data) << " ";
            rightptr = rightptr->right;
        }
        cout << "\n";
        downptr = downptr->down;
    }
}
//Driver Code
int main() {
    int mat[3][3] = {
         { 1, 2, 3 },
        { 4, 5, 6 },
        { 7, 8, 9 }
    };
    int n = 3, m = 3;
 
    Node* head_main = NULL; // head of our final modified doubly linked list from 2d matrix.
    Node* prev, *upper = new Node(-1); // dummy node to mark start of up pointer.
    for (int i = 0; i < n; i++) {
        Node* head_row; //row-wise head of list.
        Node *prev = new Node(-1); // dummy node to mark start of left pointer.
        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;
 
            //This is only used for 1st row.
            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; // To hold the value of matrix
 
        // 4 pointers for left, right, up, down for
        // markings.
        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)
    {
        // Require 2 pointers, downptr and rightptr, for
        // rows and columns.
        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; // head of our final modified doubly
                    // linked list from 2d matrix.
        Node prev, upper
                   = new Node(-1); // dummy node to mark
                                   // start of up pointer.
        for (int i = 0; i < n; i++) {
            Node head_row
                = new Node(-1); // row-wise head of list.
            prev = new Node(-1); // dummy node to mark start
                                 // of left pointer.
            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;
 
                // This is only used for 1st row.
                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);
    }
}
 
// This code is contributed by Tapesh(tapeshdua420)


Python3




# Python implementation of construction
# of a Doubly linked linked list from 2D Matrix
 
 
class Node:
    def __init__(self, data):
        self.data = data  # To hold the value of matrix
 
        # 4 pointers for left, right, up, down for markings.
        self.left = None
        self.right = None
        self.up = None
        self.down = None
 
 
def printList(head):
    # 4 pointers for left, right, up, down for markings.
    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 of our final modified doubly linked list from 2d matrix.
    head_main = None
    prev = None
    upper = Node(-1)  # dummy node to mark start of up pointer.
    for i in range(n):
        head_row = None  # row-wise head of list.
        prev = Node(-1)  # dummy node to mark start of left pointer.
        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
 
            # This is only used for 1st row.
            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)
 
# This code is contributed by Tapesh (tapeshdua420)


C#




// C# implementation of construction
// of a Doubly linked linked list from 2D Matrix
using System;
 
class Program {
 
  // Driver Code
  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; // head of our final modified doubly
    // linked list from 2d matrix.
    Node prev, upper
      = new Node(-1); // dummy node to mark
    // start of up pointer.
 
    for (int i = 0; i < n; i++) {
      Node head_row
        = new Node(-1); // row-wise head of list.
      prev = new Node(-1); // dummy node to mark start
      // of left pointer.
 
      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;
 
        // This is only used for 1st row.
        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)
 
  {
    // Require 2 pointers, downptr and rightptr, for
    // rows and columns.
    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; // To hold the value of matrix
 
  // 4 pointers for left, right, up, down for markings.
  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;
  }
}
 
// This code is contributed by Tapesh(tapeshdua420)


Javascript




<script>
 
// JavaScript implementation of construction
// of a Doubly linked linked list from 2D Matrix
class Node {
 
    // To hold the value of matrix
    // 4 pointers for left, right, up, down for markings.
    constructor(x)
    {
        this.data = x;
        this.left = null;
        this.right = null;
        this.up = null;
        this.down = null;
    }
}
 
function print(head)
{
 
    // Require 2 pointers, downptr and rightptr, for rows and columns.
    let downptr = head;
    let rightptr;
    while (downptr) {
        rightptr = downptr;
        while (rightptr) {
            document.write(rightptr.data," ");
            rightptr = rightptr.right;
        }
        document.write("</br>");
        downptr = downptr.down;
    }
}
 
// Driver Code
let mat = [
        [ 1, 2, 3 ],
        [ 4, 5, 6 ],
        [ 7, 8, 9 ]
];
let n = 3, m = 3;
 
let head_main = null; // head of our final modified doubly linked list from 2d matrix.
let prev, upper = new Node(-1); // dummy node to mark start of up pointer.
for (let i = 0; i < n; i++) {
    let head_row; //row-wise head of list.
    let prev = new Node(-1); // dummy node to mark start of left pointer.
    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;
 
        //This is only used for 1st row.
        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)
         
// This code is contributed by shinjanpatra
 
</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

When is Doubly Linked List more Efficient than Singly Linked List?
Did you know there are some cases where a Doubly Linked List is more efficient than a Singly Linked List, even though it takes more memory compared to a Singly Linked List? What are those Cases? Well, we will discuss that in the following article, But first, let's talk about Singly and linked lists: What is a Singly Linked List?A singly linked list
4 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 “doubly” highlights that there are two links per
3 min read
XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
In this post, we're going to talk about how XOR linked lists are used to reduce the memory requirements of doubly-linked lists. We know that each node in a doubly-linked list has two pointer fields which contain the addresses of the previous and next node. On the other hand, each node of the XOR linked list requires only a single pointer field, whi
15+ 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 a new node at the beginning.A function to travers
10 min read
Difference between Singly linked list and Doubly linked list
Introduction to Singly linked list : A singly linked list is a set of nodes where each node has two fields 'data' and 'link'. The 'data' field stores actual piece of information and 'link' field is used to point to next node. Basically the 'link' field stores the address of the next node.  Introduction to Doubly linked list : A Doubly Linked List (
2 min read
Construct a linked list from 2D matrix (Iterative Approach)
Given a matrix, the task is to construct a linked list matrix in which each node is connected to its right and down node. Example: Input: [1 2 3 4 5 6 7 8 9] Output: 1 -&gt; 2 -&gt; 3 -&gt; NULL | | | v v v 4 -&gt; 5 -&gt; 6 -&gt; NULL | | | v v v 7 -&gt; 8 -&gt; 9 -&gt; NULL | | | v v v NULL NULL NULL A recursive solution for this problem has been
12 min read
Construct a linked list from 2D matrix
Given a matrix. Convert it into a linked list matrix such that each node is connected to its next right and down node. Input : 2D matrix 1 2 34 5 67 8 9Output :1 -&gt; 2 -&gt; 3 -&gt; NULL| | |v v v4 -&gt; 5 -&gt; 6 -&gt; NULL| | |v v v7 -&gt; 8 -&gt; 9 -&gt; NULL| | |v v vNULL NULL NULL Question Source: Factset Interview Experience | Set 9 Recomme
13 min read
Generate matrix from given Sparse Matrix using Linked List and reconstruct the Sparse Matrix
Given a sparse matrix mat[][] of dimensions N*M, the task is to construct and represent the original matrix using a Linked List and reconstruct the givensparse matrix. Examples: Input: mat[][] = {{0, 1, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 0, 2, 0, 0}, {0, 3, 0, 0, 4}, {0, 0, 5, 0, 0}}Output:Linked list representation: (4, 2, 5) ? (3, 4, 4) ? (3, 1, 3) ?
15+ min read
Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
Given two sorted linked lists, construct a linked list that contains maximum sum path from start to end. The result list may contain nodes from both input lists. When constructing the result list, we may switch to the other input list only at the point of intersection (which mean the two node with the same value in the lists). You are allowed to us
14 min read
Construct a square Matrix whose parity of diagonal sum is same as size of matrix
Given an integer N representing the size of the matrix, the task is to construct a square matrix N * N which have an element from 1 to N2 such that the parity of the sum of its diagonals is equal to the parity of integer N. Examples: Input: N = 4Output:1 2 3 4 8 7 6 59 10 11 1216 15 14 13Explanation:Sum of diagonal = 32 and 36 and integer N = 4, al
6 min read
Construct a Matrix such that each cell consists of sum of adjacent elements of respective cells in given Matrix
Given a matrix arr[][] of dimensions N * M, the task is to generate a matrix such that any cell (r, c) stores the sum of adjacent elements present horizontally, vertically, and diagonally in the given matrix. Examples: Input: arr[][] = {{1, 3}, {2, 4}}Output: {{9, 7}, {8, 6}}Explanation: Matrix is constructed by the following operations: For cell (
9 min read
Circular Matrix (Construct a matrix with numbers 1 to m*n in spiral way)
Given two values m and n, fill a matrix of size 'm*n' in a spiral (or circular) fashion (clockwise) with natural numbers from 1 to m*n. Examples: Input : m = 4, n = 4 Output : 1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7 Input : m = 3, n = 4 Output : 1 2 3 4 10 11 12 5 9 8 7 6 The idea is based on Print a given matrix in spiral form. We create a matrix o
10 min read
Reverse a Doubly linked list using recursion
Given a doubly linked list. Reverse it using recursion. Original Doubly linked list Reversed Doubly linked list We have discussed Iterative solution to reverse a Doubly Linked List Algorithm: If list is empty, return Reverse head by swapping head-&gt;prev and head-&gt;next If prev = NULL it means that list is fully reversed. Else reverse(head-&gt;p
9 min read
Find quadruplets with given sum in a Doubly Linked List
Given a sorted doubly linked list and an integer X, the task is to print all the quadruplets in the doubly linked list whose sum is X. Examples: Input: LL: -3 ? 1 ? 2 ? 3 ? 5 ? 6, X = 7Output:-3 2 3 5 -3 3 1 6Explanation: The quadruplets having sum 7( = X) are: {-3, 2, 3, 5}, {-3, 3, 1, 6}. Input: LL: -2 ? -1 ? 0 ? 0 ? 1 ? 2, X = 0Output:-2 -1 1 2-
14 min read
Reverse a Doubly Linked List without swapping nodes
Write a program to reverse the given Doubly Linked List. See below diagrams for example. (a) Original Doubly Linked List (b) Reversed Doubly Linked List Approach: In the previous post, doubly linked list is being reversed by swapping prev and next pointers for all nodes, changing prev of the head (or start) and then changing the head pointer in the
10 min read
Reverse a Doubly Linked List by swapping data
Given a Doubly Linked List, we are asked to reverse the list in place without using any extra space. Examples: Input : 1 &lt;--&gt; 2 &lt;--&gt; 5 &lt;--&gt; 6 &lt;--&gt; 7 Output : 7 &lt;--&gt; 6 &lt;--&gt; 5 &lt;--&gt; 2 &lt;--&gt; 1 Input : 11 &lt;--&gt; 22 &lt;--&gt; 33 &lt;--&gt; 22 &lt;--&gt; 1 Output : 1 &lt;--&gt; 22 &lt;--&gt; 33 &lt;--
10 min read
Find the largest node in Doubly linked list
Given a doubly-linked list, find the largest node in the doubly linked list. Examples: Input: 10-&gt;8-&gt;4-&gt;23-&gt;67-&gt;88 Largest node is: 88 Output: 88 Input : 34-&gt;2-&gt;78-&gt;18-&gt;120-&gt;39-&gt;7 Largest node is: 120 Output :120 Approach Used: Initialize the temp and max pointer to head nodes. Traverse the whole list. if temp's dat
10 min read
Reverse a doubly linked list in groups of given size
Given a doubly linked list containing n nodes. The problem is to reverse every group of k nodes in the list. Examples: Prerequisite: Reverse a doubly linked list | Set-2. Approach: Create a recursive function say reverse(head, k). This function receives the head or the first node of each group of k nodes. It reverses those groups of k nodes by appl
15+ min read
Priority Queue using Doubly Linked List
Given Nodes with their priority, implement a priority queue using doubly linked list. Prerequisite : Priority Queue push(): This function is used to insert a new data into the queue.pop(): This function removes the element with the lowest priority value from the queue.peek() / top(): This function is used to get the lowest priority element in the q
11 min read
Applications, Advantages and Disadvantages of Circular Doubly Linked List
The circular doubly linked list is a combination of the doubly linked list and the circular linked list. It means that this linked list is bidirectional and contains two pointers and the last pointer points to the first pointer. Applications of Circular Doubly Linked List: Music and video playlists: Circular doubly linked lists are commonly used to
4 min read
Large number arithmetic using doubly linked list
Given two very large numbers in form of strings. Your task is to apply different arithmetic operations on these strings. Prerequisite : Doubly Linked List. Examples: Input : m : 123456789123456789123456789123456789123456789123456789 n : 456789123456789123456789123456789123456789123456789 Output : Product : 563937184884934839205932493526930147847927
13 min read
Sorted insert in a doubly linked list with head and tail pointers
A Doubly linked list is a linked list that consists of a set of sequentially linked records called nodes. Each node contains two fields that are references to the previous and to the next node in the sequence of nodes. The task is to create a doubly linked list by inserting nodes such that list remains in ascending order on printing from left to ri
10 min read
Sort the biotonic doubly linked list | Set-2
Sort the given biotonic doubly linked list. A biotonic doubly linked list is a doubly-linked list which is first increasing and then decreasing. A strictly increasing or a strictly decreasing list is also a biotonic doubly linked list. Examples: Input : 2 5 7 12 10 6 4 1 Output : 1 2 4 5 6 7 10 12 Input : 20 17 14 8 3 Output : 3 8 14 17 20Recommend
15 min read
Delete all the nodes from the doubly linked list that are greater than a given value
Given a doubly linked list containing N nodes and a number X, the task is to delete all the nodes from the list that are greater than the given value X. Examples: Input: 10 8 4 11 9, X = 9 Output: 8 4 9 Explanation: 10 and 11 are greater than 9. So after removing them doubly linked list will become 8 4 9. Input: 4 4 2 1 3 5, X = 2 Output: 2 1 Appro
11 min read
Delete all the even nodes from a Doubly Linked List
Given a doubly linked list containing N nodes, the task is to delete all the even nodes from the list. Examples: Input: Initial List = 15 &lt;=&gt; 16 &lt;=&gt; 6 &lt;=&gt; 7 &lt;=&gt; 17 Output: Final List = 15 &lt;=&gt; 7 &lt;=&gt; 17Explanation: 16 and 6 are even nodes. So we need to delete them. Input: Initial List = 5 &lt;=&gt; 3 &lt;=&gt; 6
11 min read
Remove all the Even Digit Sum Nodes from a Doubly Linked List
Given a Doubly linked list containing N nodes, the task is to remove all the nodes from the list which contains elements whose digit sum is even. Examples: Input: DLL = 18 &lt;=&gt; 15 &lt;=&gt; 8 &lt;=&gt; 9 &lt;=&gt; 14 Output: 18 &lt;=&gt; 9 &lt;=&gt; 14 Explanation: The linked list contains : 18 -&gt; 1 + 8 = 9 15 -&gt; 1 + 5 = 6 8 -&gt; 8 9 -
13 min read
Bubble Sort On Doubly Linked List
Sort the given doubly linked list using bubble sort. Examples: Input : 5 4 3 2 1 Output : 1 2 3 4 5 Input : 2 1 3 5 4 Output :1 2 3 4 5 Explanation: As we do in the bubble sort, here also we check elements of two adjacent nodes whether they are in ascending order or not, if not then we swap the element. We do this until every element gets its origi
8 min read
Convert an Array to a Circular Doubly Linked List
Prerequisite: Doubly Linked list, Circular Linked List, Circular Doubly Linked ListGiven an array of N elements. The task is to write a program to convert the array into a circular doubly linked list. The idea is to start traversing the array and for every array element create a new list node and assign the prev and next pointers of this node accor
8 min read
Reverse a doubly circular linked list
The problem is to reverse the given doubly circular linked list. Examples: Input: Output: Algorithm: insertEnd(head, new_node) Declare last if head == NULL then new_node-&gt;next = new_node-&gt;prev = new_node head = new_node return last = head-&gt;prev new_node-&gt;next = head head-&gt;prev = new_node new_node-&gt;prev = last last-&gt;next = new_n
11 min read
Product of all prime nodes in a Doubly Linked List
Given a doubly linked list containing N nodes. The task is to find the product of all prime nodes. Example: Input: List = 15 &lt;=&gt; 16 &lt;=&gt; 6 &lt;=&gt; 7 &lt;=&gt; 17 Output: Product of Prime Nodes: 119 Input: List = 5 &lt;=&gt; 3 &lt;=&gt; 4 &lt;=&gt; 2 &lt;=&gt; 9 Output: Product of Prime Nodes: 30 Approach: Initialize a pointer temp with
10 min read