Posted on by Kalkicode
Code Doubly linked list

construct a linked list from 2d matrix in scala

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

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