Sorted order insertion of linked list in node js

Js program for Sorted order insertion of linked list. Here problem description and explanation.

/*
    Node JS program for
    Add node in sorted order of linked list
*/
// Linked list node
class LinkNode
{
	constructor(data)
	{
		this.data = data;
		this.next = null;
	}
}
class SingleLL
{
	constructor()
	{
		this.head = null;
	}
	// Add new node in sorted order
	sortedAdd(data)
	{
		// Create new node
		var node = new LinkNode(data);
		if (this.head == null || 
            this.head.data >= data)
		{
			// When linked list empty
			// or new nodes are adding at beginning
			node.next = this.head;
			this.head = node;
		}
		else
		{
			var temp = this.head;
			// Find position to add new node
			while (temp.next != null && 
                   temp.next.data < data)
			{
				// Visit to next node
				temp = temp.next;
			}
			node.next = temp.next;
			// Add new node
			temp.next = 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;
		}
		process.stdout.write(" NULL\n");
	}
}

function main()
{
	var sll = new SingleLL();
	// Add Linked list node
	sll.sortedAdd(1);
	sll.sortedAdd(-3);
	sll.sortedAdd(9);
	sll.sortedAdd(4);
	sll.sortedAdd(11);
	sll.sortedAdd(-7);
	process.stdout.write(" Linked List \n");
	// -7 → -3 → 1 → 4 → 9 → 11 → NULL
	sll.display();
}
// Start program execution
main();

Output

 Linked List
-7 → -3 → 1 → 4 → 9 → 11 →  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