Skip to main content

Insert node at beginning of doubly linked list in kotlin

Kotlin program for Insert node at beginning of doubly linked list. Here problem description and other solutions.

// Kotlin Program For
// Insert new node at beginning 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 ? ;
	constructor()
	{
		this.head = null;
	}
	// Insert new node at beginning position
	fun insert(value: Int): Unit
	{
		// Create a node
		val node: LinkNode = LinkNode(value);
		node.next = this.head;
		// When linked list is not empty
		if (this.head != null)
		{
			this.head?.prev = node;
		}
		// Make new head
		this.head = node;
	}
	// Display node element of doubly linked list
	fun display(): Unit
	{
		if (this.head == null)
		{
			println("Empty Linked List");
		}
		else
		{
			println("  Doubly Linked List Element :");
			// Get first node of linked list
			var temp: LinkNode ? = this.head;
			// iterate linked list 
			while (temp != null)
			{
				// Display node value
				print("  " + temp.data);
				// Visit to next node
				temp = temp.next;
			}
		}
	}
}
fun main(args: Array < String > ): Unit
{
	val dll: DoublyLinkedList = DoublyLinkedList();
	// Insert following linked list nodes
	dll.insert(70);
	dll.insert(60);
	dll.insert(50);
	dll.insert(40);
	dll.insert(30);
	dll.insert(20);
	dll.insert(10);
	//  NULL <- 10 <--> 20 <--> 30 <--> 40 <--> 50 <--> 60 <--> 70->NULL
	dll.display();
}

Output

  Doubly Linked List Element :
  10  20  30  40  50  60  70




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