Remove duplicates from unsorted linked list in scala

Scala program for Remove duplicates from unsorted linked list. Here problem description and explanation.

// Scala Program to 
// Delete duplicate nodes in unsorted linked list
class LinkNode(var data: Int,
	var next: LinkNode)
{
	def this(data: Int)
	{
		this(data, null);
	}
}
class LinkedList(var head: LinkNode,
	var tail: LinkNode)
{
	// Class constructors
	def this()
	{
		this(null, null);
	}
	// Insert new element at end position
	def insert(value: Int): Unit = {
		// Create new node
		var node: LinkNode = new LinkNode(value);
		if (this.head == null)
		{
			// Add first node
			this.head = node;
		}
		else
		{
			// Add new node at the last position
			this.tail.next = node;
		}
		// Make new tail 
		this.tail = node;
	}
	// Display all node value
	def display(): Unit = {
		if (this.head != null)
		{
			print("Linked List Element :");
			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");
		}
	}
	def removeNode(): Unit = {
		if (this.head == null)
		{
			// When linked list empty
			print("Empty Linked list");
		}
		else
		{
			// Auxiliary variable
			var temp: LinkNode = this.head;
			var hold: LinkNode = null;
			var initial: LinkNode = null;
			var current: LinkNode = null;
			// Outer loop
			while (temp != null)
			{
				// New last node
				this.tail = temp;
				current = temp;
				initial = current.next;
				// Inner loop
				// Remove all node which value is similar to temp node
				while (initial != null)
				{
					if (temp.data == initial.data)
					{
						// Get remove node
						hold = initial;
					}
					else
					{
						current = initial;
					}
					// Visit to next node
					initial = initial.next;
					if (hold != null)
					{
						current.next = initial;
						// remove node
						hold = null;
					}
				}
				// Visit to next node
				temp = temp.next;
			}
		}
	}
}
object Main
{
	def main(args: Array[String]): Unit = {
		// new linked list
		var task: LinkedList = new LinkedList();
		// Add tested element
		task.insert(1);
		task.insert(2);
		task.insert(9);
		task.insert(4);
		task.insert(9);
		task.insert(3);
		task.insert(1);
		task.insert(7);
		task.insert(2);
		task.insert(1);
		println("\nBefore Delete ");
		task.display();
		task.removeNode();
		println("\nAfter Delete ");
		task.display();
	}
}

Output

Before Delete
Linked List Element :  1  2  9  4  9  3  1  7  2  1
After Delete
Linked List Element :  1  2  9  4  3  7


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







© 2021, kalkicode.com, All rights reserved