Skip to main content

Check linked list is circular or not in typescript

Ts program for Check linked list is circular or not . Here problem description and other solutions.

// TypeScript Program for
// Check linked list is circular or not

// Define class of linked list Node
class LinkNode
{
	public data: number;
	public next: LinkNode;
	constructor(data: number)
	{
		this.data = data;
		this.next = null;
	}
}
class LinkedList
{
	public head: LinkNode;
	// Class constructor
	constructor()
	{
		this.head = null;
	}
	// Check circular linked list or not
	// Note that this function is not capable to detect loop
	public boolean isCircular()
	{
		if (this.head == null)
		{
			// Case when linked list is empty
			return false;
		}
		else
		{
			var temp = 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;
		}
	}
	public static main(args: string[])
	{
		var ll = new LinkedList();
		// insert element of linked list
		ll.head = new LinkNode(1);
		ll.head.next = new LinkNode(2);
		ll.head.next.next = new LinkNode(3);
		ll.head.next.next.next = new LinkNode(4);
		ll.head.next.next.next.next = new LinkNode(5);
		if (ll.isCircular())
		{
			console.log("Yes");
		}
		else
		{
			console.log("No");
		}
		// Connect last node to head
		ll.head.next.next.next.next.next = ll.head;
		if (ll.isCircular())
		{
			console.log("Yes");
		}
		else
		{
			console.log("No");
		}
	}
}
LinkedList.main([]);
/*
 file : code.ts
 tsc --target es6 code.ts
 node code.js
 */

Output

No
Yes




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