Delete middle node from linked list in js

Js program for Delete middle node from linked list. Here problem description and explanation.

/*
    Node JS program for
    Delete middle node of linked list
*/
// Linked list node
class LinkNode
{
	constructor(data)
	{
		this.data = data;
		this.next = null;
	}
}
class SingleLL
{
	constructor()
	{
		this.head = null;
	}
	// Adding new node at beginning of linked list
	addNode(data)
	{
		// Create new node
		var node = new LinkNode(data);
		// Connect current node to previous head
		node.next = this.head;
		this.head = node;
	}
	// Display linked list element
	display()
	{
		if (this.head == null)
		{
			return;
		}
		var temp = this.head;
		// iterating linked list elements
		while (temp != null)
		{
			// Display node value
			process.stdout.write(temp.data + " → ");
			// Visit to next node
			temp = temp.next;
		}
		process.stdout.write(" NULL\n");
	}
	// Delete the middle node of linked list
	deleteMid()
	{
		if (this.head == null)
		{
			// When linked list are no elements
			console.log("Empty Linked List");
		}
		else if (this.head.next == null && this.head.next.next == null)
		{
			// When linked list are less than  of 3 nodes
			console.log("Less then 3 node of linked list");
		}
		else
		{
			var temp = this.head;
			var midPrevious = null;
			// Find the middle and its previous node
			while (temp != null && temp.next != null && 
                   temp.next.next != null)
			{
				if (midPrevious == null)
				{
					// When first node
					midPrevious = temp;
				}
				else
				{
					// Visit to next node
					midPrevious = midPrevious.next;
				}
				// Visit to next second next node
				temp = temp.next.next;
			}
			// Get the node which is deleting 
			temp = midPrevious.next;
			// Show deleted node
			console.log("Delete node : " + temp.data);
			// Change link
			midPrevious.next = temp.next;
		}
	}
}

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

Output

Before Delete middle node
7 → 6 → 5 → 4 → 3 → 2 → 1 →  NULL
Delete node : 4
After Delete middle node
7 → 6 → 5 → 3 → 2 → 1 →  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