Posted on by Kalkicode
Code Doubly linked list

construct a linked list from 2d matrix in kotlin

Kotlin program for construct a linked list from 2d matrix. Here more information.

// Kotlin program for
// Construct a linked list from 2D matrix
class LinkNode
{
	var data: Int;
	var next: LinkNode ? ;
	var down: LinkNode ? ;
	constructor(data: Int)
	{
		this.data = data;
		this.next = null;
		this.down = null;
	}
}
class DoublyLinkedList
{
	var head: LinkNode ? ;
	constructor()
	{
		this.head = null;
	}
	fun display(): Unit
	{
		if (this.head == null)
		{
			print("Empty linked list");
		}
		else
		{
			var front: LinkNode ? = this.head;
			var right: LinkNode ? ;
			while (front != null)
			{
				right = front;
				while (right != null)
				{
					print("  " + right.data );
					right = right.next;
				}
				print("\n");
				// Visit to down node
				front = front.down;
			}
		}
	}
	fun insertData(matrix: Array < Array < Int >> , 
                   rows: Int, cols: Int): Unit
	{
		// Some auxiliary variables
		var levelHead: LinkNode ? = null;
		var root: LinkNode ? ;
		var perv: LinkNode ? ;
		var i: Int = 0;
		var j: Int = 0;
		// Add first row elements into result list 
		while (i < cols)
		{
			if (this.head == null)
			{
				// Add first node
				this.head = LinkNode(matrix[0][i]);
				levelHead = this.head;
			}
			else
			{
				// next head
				levelHead?.next = LinkNode(matrix[0][i]);
				levelHead = levelHead?.next;
			}
			i += 1;
		}
		// 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 = LinkNode(matrix[i][j]);
				if (root == null)
				{
					root = levelHead?.down;
					perv = root;
				}
				else
				{
					perv?.next = levelHead?.down;
					perv = levelHead?.down;
				}
				levelHead = levelHead?.next;
				j += 1;
			}
			levelHead = root;
			// reset col
			j = 0;
			// change row
			i += 1;
		}
	}
}
fun main(args: Array < String > ): Unit
{
	val dll: DoublyLinkedList = DoublyLinkedList();
	// Create 2D metrix
	val matrix: Array < Array < Int >> = arrayOf(
      arrayOf(1, 6, 9, 2, -9), 
      arrayOf(2, 5, -5, 7, 1), 
      arrayOf(3, 4, 1, 8, 2)
    );
	val rows: Int = matrix.count();
	val cols: Int = matrix[0].count();
	dll.insertData(matrix, rows, cols);
	dll.display();
}

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