Sum of smaller elements of nodes in a linked list in kotlin
Kotlin program for Sum of smaller elements of nodes in a linked list. Here problem description and other solutions.
/*
Kotlin program for
Sum of smallest element of linked list
*/
// Linked list node
class LinkNode
{
var a: Int;
var b: Int;
var next: LinkNode ? ;
constructor(a: Int, b: Int)
{
this.a = a;
this.b = b;
this.next = null;
}
}
class SingleLL
{
var head: LinkNode ? ;
var tail: LinkNode ? ;
constructor()
{
this.head = null;
this.tail = null;
}
fun insert(a: Int, b: Int): Unit
{
val node: LinkNode = LinkNode(a, b);
if (this.head == null)
{
// Add first node
this.head = node;
}
else
{
// Add node at the end position
this.tail?.next = node;
}
// new last 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.a + "," + temp.b + ") →");
// Visit to next node
temp = temp.next;
}
println(" NULL");
}
// Find the sum of smaller elements of
// every node in a linked list
fun nodeSum(): Int
{
var result: Int = 0;
var temp: LinkNode ? = this.head;
if (temp == null)
{
println("Empty linked list");
}
else
{
// Iterate the linked list
// And
// Sum of smallest key in every node of linked list
while (temp != null)
{
if (temp.a > temp.b)
{
// When key b is small
result += temp.b;
}
else
{
// When key a is small
result += temp.a;
}
// Visit to next node
temp = temp.next;
}
}
return result;
}
}
fun main(args: Array < String > ): Unit
{
val sll: SingleLL = SingleLL();
// Add pair
// (3,9) → (11,4) → (3,3) → (6,1) → (2,9) → (4,7) → NULL
sll.insert(3, 9);
sll.insert(11, 4);
sll.insert(3, 3);
sll.insert(6, 1);
sll.insert(2, 9);
sll.insert(4, 7);
println(" Linked List");
sll.display();
println(" Result : " + sll.nodeSum());
}
Output
Linked List
(3,9) → (11,4) → (3,3) → (6,1) → (2,9) → (4,7) → NULL
Result : 17
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