Skip to main content

Find length of circular linked list in typescript

Ts program for Find length of circular linked list . Here problem description and other solutions.

// TypeScript program for
// Count number of nodes in circular linked list 

// Define class of linked list Node
class LinkNode
{
	public data: number;
	public next: LinkNode;
	constructor(data: number, first: LinkNode)
	{
		this.data = data;
		this.next = first;
	}
}
class CircularLinkedList
{
	public head: LinkNode;
	// Class constructor
	constructor()
	{
		this.head = null;
	}
	// Insert node at end of circular linked list
	public insert(value: number)
	{
		// Create a new node
		var node = new LinkNode(value, this.head);
		if (this.head == null)
		{
			// First node of linked list
			this.head = node;
			node.next = this.head;
		}
		else
		{
			var temp = this.head;
			// Find the last node
			while (temp.next != this.head)
			{
				// Visit to next node
				temp = temp.next;
			}
			// Add new node at the last 
			temp.next = node;
		}
	}
	public number countNode()
	{
		if (this.head == null)
		{
			return 0;
		}
		// Start with second node
		var temp = this.head.next;
		// This is used to count linked node
		var count = 1;
		// iterate circular linked list
		while (temp != this.head)
		{
			count += 1;
			// Visit to next node
			temp = temp.next;
		}
		return count;
	}
	public static main(args: string[])
	{
		var cll = new CircularLinkedList();
		// Add nodes
		cll.insert(1);
		cll.insert(3);
		cll.insert(5);
		cll.insert(7);
		cll.insert(9);
		cll.insert(11);
		// Display result
		console.log(cll.countNode());
	}
}
CircularLinkedList.main([]);
/*
 file : code.ts
 tsc --target es6 code.ts
 node code.js
 */

Output

6




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