Convert singly linked list to circular list in kotlin
Kotlin program for Convert singly linked list to circular list. Here more information.
// Kotlin program for
// Convert singly linked list into circular list
// Define class of linked list Node
class LinkNode
{
var data: Int;
var next: LinkNode ? ;
constructor(data: Int)
{
this.data = data;
this.next = null;
}
}
class LinkedList
{
var head: LinkNode ? ;
// Class constructor
constructor()
{
this.head = null;
}
// Check circular linked list or not
// Note that this function is not capable to detect loop
fun isCircular(): Boolean
{
if (this.head == null)
{
// Case when linked list is empty
return false;
}
else
{
var temp: LinkNode ? = this.head;
while (temp != null)
{
// Visit to next node
temp = temp.next;
if (temp == this.head)
{
// When detecting circular node
return true;
}
}
// When not circular linked list
return false;
}
}
// Display node element of linked list
fun display(): Unit
{
if (this.head == null)
{
println("Empty Linked List");
}
else
{
print("Linked List Element :");
var temp: LinkNode ? = this.head;
// Iterate linked list
while (temp != null)
{
// Display node
print(" " + temp.data);
// Visit to next node
temp = temp.next;
if (temp == this.head)
{
// Stop iteration
return;
}
}
println();
}
}
// Coverted circular Linked list
fun makeCircular(): Unit
{
if (this.head == null)
{
println("Empty Linked List");
}
else
{
var temp: LinkNode ? = this.head;
// Find last node
while (temp?.next != null)
{
temp = temp.next;
if (temp == this.head)
{
// Already circular Linked list
return;
}
}
// Connect last node to first node
temp?.next = this.head;
}
}
}
fun main(args: Array < String > ): Unit
{
val ll: LinkedList = LinkedList();
// Insert element of linked list
ll.head = LinkNode(1);
ll.head?.next = LinkNode(2);
ll.head?.next?.next = LinkNode(3);
ll.head?.next?.next?.next = LinkNode(4);
ll.head?.next?.next?.next?.next = LinkNode(5);
ll.head?.next?.next?.next?.next?.next = LinkNode(6);
ll.head?.next?.next?.next?.next?.next?.next = LinkNode(7);
ll.display();
if (ll.isCircular())
{
println("Circular Yes");
}
else
{
println("Circular No");
}
println("After Convert");
ll.makeCircular();
if (ll.isCircular())
{
println("Circular Yes");
}
else
{
println("Circular No");
}
}
Output
Linked List Element : 1 2 3 4 5 6 7
Circular No
After Convert
Circular Yes
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