Skip to main content

Alternating split of singly linked list in scala

Scala program for Alternating split of singly linked list. Here problem description and other solutions.

// Scala program for
// Alternating split of a given singly linked list

// Node of LinkedList
class LinkNode(var data: Int,
	var next: LinkNode)
{
	def this(data: Int)
	{
		// Set node value
		this(data, null);
	}
}
class MyLinkedList(var head: LinkNode)
{
	def this()
	{
		this(null);
	}
	// Add new node at the end of linked list
	def insert(value: Int): Unit = {
		// Create a new node
		var node: LinkNode = new LinkNode(value);
		if (this.head == null)
		{
			this.head = node;
		}
		else
		{
			var temp: LinkNode = this.head;
			// Find last node
			while (temp.next != null)
			{
				// Visit to next node
				temp = temp.next;
			}
			// Add node at last position
			temp.next = node;
		}
	}
	// Display all Linked List elements
	def display(): Unit = {
		if (this.head != null)
		{
			var temp: LinkNode = this.head;
			while (temp != null)
			{
				// Display node value
				print("  " + temp.data);
				// Visit to next node
				temp = temp.next;
			}
		}
		else
		{
			println("Empty Linked list");
		}
	}
	// Split the linked list by alternating nodes
	def splitting(): LinkNode = {
		var result: LinkNode = null;
		if (this.head != null)
		{
			// Some auxiliary variables
			var temp: LinkNode = this.head;
			var tail: LinkNode = null;
			var current: LinkNode = null;
			var prev: LinkNode = this.head;
			while (temp != null && temp.next != null)
			{
				current = temp.next;
				prev = temp;
				temp = temp.next.next;
				if (result == null)
				{
					// When first node of second linked list
					current.next = result;
					result = current;
					tail = current;
				}
				else
				{
					// Add Alternating node to end of 
					// second linked list
					current.next = tail.next;
					tail.next = current;
					tail = current;
				}
				prev.next = temp;
			}
		}
		return result;
	}
}
object Main
{
	def main(args: Array[String]): Unit = {
		var l1: MyLinkedList = new MyLinkedList();
		var l2: MyLinkedList = new MyLinkedList();
		// Add node in l1 linked list
		l1.insert(1);
		l1.insert(2);
		l1.insert(3);
		l1.insert(4);
		l1.insert(5);
		l1.insert(6);
		l1.insert(7);
		l1.insert(8);
		// Before splitting l1
		print("L1 list : ");
		l1.display();
		l2.head = l1.splitting();
		println("\nAfter splitting ");
		print("L1 list : ");
		l1.display();
		print("\nL2 list : ");
		l2.display();
	}
}

Output

L1 list :   1  2  3  4  5  6  7  8
After splitting
L1 list :   1  3  5  7
L2 list :   2  4  6  8




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