Skip to main content

Delete odd nodes from linked list in kotlin

Kotlin program for Delete odd nodes from linked list. Here problem description and explanation.

// Kotlin program for
// Delete odd nodes from linked list

// Node of Linked List
class LinkNode
{
	var data: Int;
	var next: LinkNode ? ;
	constructor(data: Int)
	{
		//Set node value
		this.data = data;
		this.next = null;
	}
}
class SingleLL
{
	var head: LinkNode ? ;
	var tail: LinkNode ? ;
	constructor()
	{
		this.head = null;
		this.tail = null;
	}
	// Add new node at the end of linked list
	fun addNode(value: Int): Unit
	{
		// Create a new node
		val node: LinkNode = LinkNode(value);
		if (this.head == null)
		{
			this.head = node;
		}
		else
		{
			this.tail?.next = node;
		}
		this.tail = node;
	}
	// Display linked list element
	fun display(): Unit
	{
		if (this.head == null)
		{
			return;
		}
		var temp: LinkNode ? = this.head;
		// iterating linked list elements
		while (temp != null)
		{
			print(""+ temp.data + " → ");
			// Visit to next node
			temp = temp.next;
		}
		print("null\n");
	}
	// Delete all odd key nodes in linked list
	fun deleteOddNodes(): Unit
	{
		// Define some auxiliary variables
		var current: LinkNode ? = this.head;
		var auxiliary: LinkNode ? = null;
		var back: LinkNode ? = null;
		// iterating linked list elements
		while (current != null)
		{
			if ((current.data % 2) != 0)
			{
				// When get odd node
				auxiliary = current;
			}
			else
			{
				back = current;
			}
			// Visit to next node
			current = current.next;
			if (auxiliary != null)
			{
				// When Deleted node exists
				if (back == null)
				{
					// When front node is odd node
					// head visit to next node
					this.head = current;
				}
				else
				{
					// When deleting centralized node
					back.next = current;
				}
				if (this.tail == auxiliary)
				{
					// When delete last node
					// Set new tail
					this.tail = back;
				}
				// Unlink deleted node 
				auxiliary.next = null;
				auxiliary = null;
			}
		}
	}
}
fun main(args: Array < String > ): Unit
{
	val sll: SingleLL = SingleLL();
	// Add linked list node
	sll.addNode(3);
	sll.addNode(1);
	sll.addNode(4);
	sll.addNode(7);
	sll.addNode(9);
	sll.addNode(6);
	sll.addNode(5);
	sll.addNode(11);
	// Before effect
	println("Before Delete Odd Key Nodes");
	// 3 → 1 → 4 → 7 → 9 → 6 → 5 → 11 → NULL
	sll.display();
	// Perform delete operation
	sll.deleteOddNodes();
	// After effect
	println("After Delete Odd Key Nodes");
	// 4 → 6 → NULL
	sll.display();
}

Output

Before Delete Odd Key Nodes
3 → 1 → 4 → 7 → 9 → 6 → 5 → 11 → null
After Delete Odd Key Nodes
4 → 6 → null




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