Skip to main content

Convert singly linked list to circular list in scala

Scala program for Convert singly linked list to circular list. Here problem description and other solutions.

// Scala program for
// Convert singly linked list into circular list
// Define class of linked list Node
class LinkNode(var data: Int,
	var next: LinkNode)
{
	def this(data: Int)
	{
		this(data, null);
	}
}
class LinkedList(var head: LinkNode)
{
	// Class constructor
	def this()
	{
		this(null);
	}
	// Check circular linked list or not
	// Note that this function is not capable to detect loop
	def isCircular(): Boolean = {
		if (this.head == null)
		{
			// Case when linked list is empty
			return false;
		}
		else
		{
			var temp: LinkNode = this.head;
			while (temp != null)
			{
				// Visit to next node
				temp = temp.next;
				if (temp == this.head)
				{
					// When detecting circular node
					return true;
				}
			}
			// When not circular linked list
			return false;
		}
	}
	// Display node element of linked list
	def display(): Unit = {
		if (this.head == null)
		{
			println("Empty Linked List");
		}
		else
		{
			print("Linked List Element :");
			var temp: LinkNode = this.head;
			// Iterate linked list
			while (temp != null)
			{
				// Display node
				print("  " + temp.data);
				// Visit to next node
				temp = temp.next;
				if (temp == head)
				{
					// Stop iteration
					return;
				}
			}
			println();
		}
	}
	// Coverted circular Linked list
	def makeCircular(): Unit = {
		if (this.head == null)
		{
			println("Empty Linked List");
		}
		else
		{
			var temp: LinkNode = this.head;
			// Find last node
			while (temp.next != null)
			{
				temp = temp.next;
				if (temp == this.head)
				{
					// Already circular Linked list
					return;
				}
			}
			// Connect last node to first node
			temp.next = this.head;
		}
	}
}
object Main
{
	def main(args: Array[String]): Unit = {
		var ll: LinkedList = new LinkedList();
		// Insert element of linked list
		ll.head = new LinkNode(1);
		ll.head.next = new LinkNode(2);
		ll.head.next.next = new LinkNode(3);
		ll.head.next.next.next = new LinkNode(4);
		ll.head.next.next.next.next = new LinkNode(5);
		ll.head.next.next.next.next.next = new LinkNode(6);
		ll.head.next.next.next.next.next.next = new LinkNode(7);
		ll.display();
		if (ll.isCircular())
		{
			println("Circular Yes");
		}
		else
		{
			println("Circular No");
		}
		println("After Convert");
		ll.makeCircular();
		if (ll.isCircular())
		{
			println("Circular Yes");
		}
		else
		{
			println("Circular No");
		}
	}
}

Output

Linked List Element :  1  2  3  4  5  6  7
Circular No
After Convert
Circular Yes




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