Skip to main content

construct a linked list from 2d matrix in typescript

Ts program for construct a linked list from 2d matrix. Here problem description and explanation.

// TypeScript program for
// Construct a linked list from 2D matrix
class LinkNode
{
	public data: number;
	public next: LinkNode;
	public down: LinkNode;
	constructor(data: number)
	{
		this.data = data;
		this.next = null;
		this.down = null;
	}
}
class DoublyLinkedList
{
	public head: LinkNode;
	constructor()
	{
		// Set inital value
		this.head = null;
	}
	public display()
	{
		if (this.head == null)
		{
			console.log("Empty linked list");
		}
		else
		{
			var front = this.head;
			var right: LinkNode = null;
			while (front != null)
			{
				right = front;
				while (right != null)
				{
					console.log(right.data + "  ");
					right = right.next;
				}
				console.log("\n");
				// Visit to down node
				front = front.down;
			}
		}
	}
	public insertData(matrix: number[][], 
      rows: number, cols: number)
	{
		// Some auxiliary variables
		var levelHead: LinkNode = null;
		var root: LinkNode = null;
		var perv: LinkNode = 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 main(args: string[])
	{
		var dll = new DoublyLinkedList();
		// Create 2D metrix
		var matrix: number[][] = [
			[1, 6, 9, 2, -9],
			[2, 5, -5, 7, 1],
			[3, 4, 1, 8, 2]
		];
		var rows = matrix.length;
		var cols = matrix[0].length;
		dll.insertData(matrix, rows, cols);
		dll.display();
	}
}
DoublyLinkedList.main([]);
/*
 file : code.ts
 tsc --target es6 code.ts
 node code.js
 */

Output

1
6
9
2
-9


2
5
-5
7
1


3
4
1
8
2





Comment

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