Delete duplicate nodes from sorted linked list in js

Js program for Delete duplicate nodes from sorted linked list. Here problem description and explanation.

/*
    Node JS program for
    Delete duplicate nodes in sorted linked list
*/
// Linked list node
class LinkNode
{
	constructor(data)
	{
		this.data = data;
		this.next = null;
	}
}
class SingleLL
{
	constructor()
	{
		this.head = null;
		this.tail = null;
	}
	// Add new node at the end of linked list
	addNode(value)
	{
		// Create a new node
		var node = new LinkNode(value);
		if (this.head == null)
		{
			this.head = node;
		}
		else
		{
			this.tail.next = node;
		}
		this.tail = node;
	}
	// Display linked list element
	display()
	{
		if (this.head == null)
		{
			return;
		}
		var temp = this.head;
		// iterating linked list elements
		while (temp != null)
		{
			process.stdout.write(temp.data + " → ");
			// Visit to next node
			temp = temp.next;
		}
		console.log(" NULL");
	}
	// Remove the duplicate nodes from sorted singly linked list
	deleteDuplicate()
	{
		if (this.head == null)
		{
			return;
		}
		else
		{
			// Auxiliary variables
			var temp = this.head.next;
			var current = this.head;
			var hold = null;
			// Find and remove duplicate
			while (temp != null)
			{
				// Check duplicate node 
				if (current.data == temp.data)
				{
					//  When node key are same
					hold = temp;
				}
				else
				{
					// When node key are not same
					current = temp;
				}
				// Visit to next node
				temp = temp.next;
				if (hold != null)
				{
					// Modified link value
					current.next = temp;
					hold = null;
				}
				else
				{
					// Change last node
					this.tail = current;
				}
			}
		}
	}
}

function main()
{
	var sll = new SingleLL();
	// Sorted Linked list node
	//  1 → 1 → 2 → 3 → 4 → 4 → 4 → 5 → 6 → 7 → NULL
	sll.addNode(1);
	sll.addNode(1);
	sll.addNode(2);
	sll.addNode(3);
	sll.addNode(4);
	sll.addNode(4);
	sll.addNode(4);
	sll.addNode(5);
	sll.addNode(6);
	sll.addNode(7);
	console.log(" Before Delete");
	sll.display();
	sll.deleteDuplicate();
	console.log(" After Delete");
	// 1 → 2 → 3 → 4 → 5 → 6 → 7 → NULL
	sll.display();
}
// Start program execution
main();

Output

 Before Delete
1 → 1 → 2 → 3 → 4 → 4 → 4 → 5 → 6 → 7 →  NULL
 After Delete
1 → 2 → 3 → 4 → 5 → 6 → 7 →  NULL


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