Delete middle node from linked list in scala

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

/*
    Scala program for
    Delete middle node of linked list
*/
// Linked list node
class LinkNode(var data: Int,
	var next: LinkNode)
{
	def this(data: Int)
	{
	
		this(data, null);
	}
}
class SingleLL(var head: LinkNode)
{
	def this()
	{
		this(null);
	}
	// Adding new node at beginning of linked list
	def addNode(data: Int): Unit = {
		// Create new node
		var node: LinkNode = new LinkNode(data);
		// Connect current node to previous head
		node.next = this.head;
		this.head = node;
	}
	// Display linked list element
	def display(): Unit = {
		if (this.head == null)
		{
			return;
		}
		var temp: LinkNode = this.head;
		// iterating linked list elements
		while (temp != null)
		{
			// Display node value
			print(""+ temp.data + " → ");
			// Visit to next node
			temp = temp.next;
		}
		print(" NULL\n");
	}
	// Delete the middle node of linked list
	def deleteMid(): Unit = {
		if (this.head == null)
		{
			// When linked list are no elements
			println("Empty Linked List");
		}
		else if (this.head.next == null && this.head.next.next == null)
		{
			// When linked list are less than  of 3 nodes
			println("Less then 3 node of linked list");
		}
		else
		{
			var temp: LinkNode = this.head;
			var midPrevious: LinkNode = 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
			println("Delete node : " + temp.data);
			// Change link
			midPrevious.next = temp.next;
		}
	}
}
object Main
{
	def main(args: Array[String]): Unit = {
		var sll: SingleLL = 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);
		println("Before Delete middle node");
		sll.display();
		// Delete middle node
		sll.deleteMid();
		println("After Delete middle node");
		sll.display();
	}
}

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