Delete last node of linked list in scala

Scala program for Delete last node of linked list. Here problem description and explanation.

/*
    Scala program for
    Delete the last node of singly 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,
	var tail: LinkNode)
{
	def this()
	{
		this(null, null);
	}
	// Add new node at the end of linked list
	def addNode(value: Int): Unit = {
		// Create a new node
		var node: LinkNode = new LinkNode(value);
		if (this.head == null)
		{
			this.head = node;
		}
		else
		{
			this.tail.next = node;
		}
		// Set new last node
		this.tail = node;
	}
	// Display linked list element
	def display(): Unit = {
		if (this.head == null)
		{
			println("Empty Linked List");
			return;
		}
		var temp: LinkNode = this.head;
		// iterating linked list elements
		while (temp != null)
		{
			print(""+ temp.data + " → ");
			// Visit to next node
			temp = temp.next;
		}
		println("NULL");
	}
	// Delete last node of singly linked list
	def deleteLastNode(): Unit = {
		if (this.head == null)
		{
			println("Empty Linked List");
			return;
		}
		else
		{
			var temp: LinkNode = this.head;
			var find: LinkNode = null;
			// Find second last node
			while (temp.next != null)
			{
				find = temp;
				temp = temp.next;
			}
			if (find == null)
			{
				// Delete head node of linked list
				this.head = null;
				this.tail = null;
			}
			else
			{
				// Set new last node
				this.tail = find;
				find.next = null;
			}
		}
	}
}
object Main
{
	def main(args: Array[String]): Unit = {
		var sll: SingleLL = new SingleLL();
		// Linked list
		// 1 → 2 → 3 → 4 → 5 → 6 → NULL
		sll.addNode(1);
		sll.addNode(2);
		sll.addNode(3);
		sll.addNode(4);
		sll.addNode(5);
		sll.addNode(6);
		println("Before Delete ");
		sll.display();
		sll.deleteLastNode();
		println("After Delete ");
		sll.display();
	}
}

Output

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