construct a linked list from 2d matrix in c#
Csharp program for construct a linked list from 2d matrix. Here problem description and other solutions.
// Include namespace system
using System;
// Csharp program for
// Construct a linked list from 2D matrix
public class LinkNode
{
public int data;
public LinkNode next;
public LinkNode down;
public LinkNode(int data)
{
this.data = data;
this.next = null;
this.down = null;
}
}
public class DoublyLinkedList
{
public LinkNode head;
public DoublyLinkedList()
{
// Set inital value
this.head = null;
}
public void display()
{
if (this.head == null)
{
Console.Write("Empty linked list");
}
else
{
var front = this.head;
LinkNode right = null;
while (front != null)
{
right = front;
while (right != null)
{
Console.Write(right.data + " ");
right = right.next;
}
Console.Write("\n");
// Visit to down node
front = front.down;
}
}
}
public void insertData(int[, ] matrix, int rows, int cols)
{
// Some auxiliary variables
LinkNode levelHead = null;
LinkNode root = null;
LinkNode perv = null;
var i = 0;
var j = 0;
// Add first row elements into result list
while (i < cols)
{
if (this.head == null)
{
// Add first node
this.head = new LinkNode(matrix[0, i]);
levelHead = this.head;
}
else
{
// next head
levelHead.next = new LinkNode(matrix[0, i]);
levelHead = levelHead.next;
}
i++;
}
// Get first element
levelHead = this.head;
i = 1;
// Add all the bottom element of each column
while (i < rows)
{
root = null;
perv = root;
while (j < cols)
{
levelHead.down = new LinkNode(matrix[i, j]);
if (root == null)
{
root = levelHead.down;
perv = root;
}
else
{
perv.next = levelHead.down;
perv = levelHead.down;
}
levelHead = levelHead.next;
j++;
}
levelHead = root;
// reset col
j = 0;
// change row
i++;
}
}
public static void Main(String[] args)
{
var dll = new DoublyLinkedList();
// Create 2D metrix
int[, ] matrix = {
{
1 , 6 , 9 , 2 , -9
},
{
2 , 5 , -5 , 7 , 1
},
{
3 , 4 , 1 , 8 , 2
}
};
var rows = matrix.GetLength(0);
var cols = matrix.GetLength(1);
dll.insertData(matrix, rows, cols);
dll.display();
}
}
Output
1 6 9 2 -9
2 5 -5 7 1
3 4 1 8 2
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment