Skip to main content

Effectively insert node at beginning of circular linked list in typescript

Ts program for Effectively insert node at beginning of circular linked list . Here problem description and other solutions.

// TypeScript Program 
// Insert node at beginning of circular linked list
// Using head and tail nodes

// Define class of linked list Node
class LinkNode
{
	public data: number;
	public next: LinkNode;
	constructor(data: number, first: LinkNode)
	{
		// Set node value
		this.data = data;
		this.next = first;
	}
}
class CircularLinkedList
{
	public head: LinkNode;
	public tail: LinkNode;
	constructor()
	{
		// Set head and tail values
		this.head = null;
		this.tail = null;
	}
	// Insert node at begining of circular linked list
	public insert(value: number)
	{
		// Create a node
		var node = new LinkNode(value, this.head);
		if (this.tail == null)
		{
			// First node of linked list
			this.tail = node;
		}
		// Make new head
		this.head = node;
		// Connecting the last node to the top of the next field
		this.tail.next = this.head;
	}
	// Display node element of circular linked list
	public display()
	{
		if (this.head == null)
		{
			console.log("Empty Linked List");
		}
		else
		{
			console.log("Linked List Element :");
			var temp = this.head;
			// iterate linked list
			while (temp != null)
			{
				// Display node
				console.log("  " + temp.data);
				if (temp == this.tail)
				{
					// Stop iteration
					// Or break;
					return;
				}
				// Visit to next node
				temp = temp.next;
			}
		}
	}
	public static main(args: string[])
	{
		var task = new CircularLinkedList();
		// Add following linked list nodes
		task.insert(8);
		task.insert(7);
		task.insert(6);
		task.insert(5);
		task.insert(4);
		task.insert(3);
		task.insert(2);
		task.insert(1);
		// Display node
		task.display();
	}
}
CircularLinkedList.main([]);
/*
 file : code.ts
 tsc --target es6 code.ts
 node code.js
 */

Output

Linked List Element :
  1
  2
  3
  4
  5
  6
  7
  8




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