Skip to main content

Segregate even and odd nodes of a linked list in node js

Js program for Segregate even and odd nodes of a linked list. Here problem description and explanation.

// Node JS Program for
// Segregate even and odd nodes in linked list

// Linked list node
class LinkNode
{
	constructor(data)
	{
		this.data = data;
		this.next = null;
	}
}
class SingleLL
{
	constructor()
	{
		this.head = null;
	}
	// Add new node at the end of linked list
	addNode(value)
	{
		// Create new node
		var node = new LinkNode(value);
		if (this.head == null)
		{
			this.head = node;
		}
		else
		{
			var temp = 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
	display()
	{
		if (this.head != null)
		{
			var temp = this.head;
			while (temp != null)
			{
				// Display node value
				process.stdout.write("  " + temp.data);
				// Visit to next node
				temp = temp.next;
			}
		}
		else
		{
			process.stdout.write("Empty Linked list\n");
		}
	}
	// Segregate even and odd element of linked list
	segregate()
	{
		if (this.head != null)
		{
			var temp = this.head;
			var hold = null;
			var odd = null;
			this.head = null;
			// Separates nodes
			while (temp != null)
			{
				hold = temp;
				temp = temp.next;
				if (hold.data % 2 == 0)
				{
					// Gets even nodes
					hold.next = this.head;
					this.head = hold;
				}
				else
				{
					// Gets odd nodes
					hold.next = odd;
					odd = hold;
				}
			}
			if (this.head != null)
			{
				// Even node are exist
				temp = this.head;
				while (temp.next != null)
				{
					temp = temp.next;
				}
				// Add remaining odd nodes
				temp.next = odd;
			}
			else
			{
				// When only odd nodes
				this.head = odd;
			}
		}
	}
}

function main()
{
	var sll = new SingleLL();
	// Create Linked List
	// 1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → 10 → NULL
	sll.addNode(1);
	sll.addNode(2);
	sll.addNode(3);
	sll.addNode(4);
	sll.addNode(5);
	sll.addNode(6);
	sll.addNode(7);
	sll.addNode(8);
	sll.addNode(10);
	console.log(" Before segregate list ");
	sll.display();
	sll.segregate();
	console.log("\n After segregate list ");
	sll.display();
}
// Start program execution
main();

Output

 Before segregate list
  1  2  3  4  5  6  7  8  10
 After segregate list
  10  8  6  4  2  7  5  3  1




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