Posted on by Kalkicode
Code Doubly linked list

Find the length of doubly linked list in kotlin

Kotlin program for Find the length of doubly linked list. Here more information.

// Kotlin program for
// Find length of doubly linked list

// Define class of linked list Node
class LinkNode
{
	var data: Int;
	var next: LinkNode ? ;
	var prev: LinkNode ? ;
	constructor(data: Int)
	{
		this.data = data;
		this.next = null;
		this.prev = null;
	}
}
class DoublyLinkedList
{
	var head: LinkNode ? ;
	var tail: LinkNode ? ;
	constructor()
	{
		this.head = null;
		this.tail = null;
	}
	// Insert new node at end position
	fun insert(value: Int): Unit
	{
		// Create a new node
		val node: LinkNode = LinkNode(value);
		if (this.head == null)
		{
			// Add first node
			this.head = node;
			this.tail = node;
			return;
		}
		// Add node at last position
		this.tail?.next = node;
		node.prev = this.tail;
		this.tail = node;
	}
	fun length(): Int
	{
		var size: Int = 0;
		// Get first node of linked list
		var temp: LinkNode ? = this.head;
		// iterate linked list 
		while (temp != null)
		{
			// Increase the size by one
			size += 1;
			// Visit to next node
			temp = temp.next;
		}
		return size;
	}
}
fun main(args: Array < String > ): Unit
{
	val dll: DoublyLinkedList = DoublyLinkedList();
	// Insert following linked list nodes
	dll.insert(4);
	dll.insert(3);
	dll.insert(2);
	dll.insert(5);
	dll.insert(3);
	println("Length  : " + dll.length());
}

Output

Length  : 5

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