Delete a node from linked list specific position in kotlin
Kotlin program for Delete a node from linked list specific position. Here problem description and explanation.
// Kotlin Program for
// Delete node at given index of linked list
// Linked list node
class LinkNode
{
var data: Int;
var next: LinkNode ? ;
constructor(data: Int)
{
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;
}
println("NULL");
}
// Delete node at given position
fun deleteAtIndex(index: Int): Unit
{
var temp: LinkNode ? = this.head;
if (this.head == null)
{
println("Empty linked list");
return;
}
else if (index < 0)
{
println("Invalid positions");
return;
}
else if (index == 1)
{
// Means deleting a first node
if (this.tail == this.head)
{
// Only one node
this.tail = null;
}
// Make second node as head
this.head = this.head?.next;
}
else
{
var count: Int = index - 1;
// iterating linked list elements and find deleted node
while (temp != null && count > 1)
{
// Visit to next node
temp = temp.next;
count -= 1;
}
if (count == 1 && temp?.next != null)
{
// Get deleted node
val n: LinkNode? = temp.next;
if (n == this.tail)
{
// When delete last node
this.tail = temp;
}
// Unlink the deleting node
temp.next = n?.next;
}
else
{
println(" Index " + index + " are not present");
return;
}
}
}
}
fun main(args: Array < String > ): Unit
{
val sll: SingleLL = SingleLL();
// Test with your index
// Note index start with 1
val index: Int = 5;
// Linked list
// 10 → 20 → 30 → 40 → 50 → 60 → 70 → 80 → NULL
sll.addNode(10);
sll.addNode(20);
sll.addNode(30);
sll.addNode(40);
sll.addNode(50);
sll.addNode(60);
sll.addNode(70);
sll.addNode(80);
println(" Before Delete Linked List");
sll.display();
// Delete node at 5-th position
sll.deleteAtIndex(index);
// Display linked list
println(" After Delete Linked List");
sll.display();
}
Output
Before Delete Linked List
10 → 20 → 30 → 40 → 50 → 60 → 70 → 80 → NULL
After Delete Linked List
10 → 20 → 30 → 40 → 60 → 70 → 80 → 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