in C Plus Plus by
Can you tell me how to check whether a linked list is circular?

1 Answer

0 votes
by

Single Linked List

Circular Linked List

Circular linked list is a variation of a linked list where the last node is pointing to the first node's information part. Therefore the last node does not point to null.

Algorithm to find whether the given linked list is circular

A very simple way to determine whether the linked list is circular or not

  • Traverse the linked list
  • Check if the node is pointing to the head.
  • If yes then it is circular.

Let's look at the snippet where we code this algorithm.

Create a structure for a linked list
Declare
-Variable to store data of the node.
-Pointer variable of struct type to store the address of next node.

function of datatype tool isCircular(firstgode){

-Store the value of first node in temp variable and make it traverse all nodes.
-temp-firstgode
-tempenext node pointed by temp(temp->next)
-run until temp is at null or firstNode

if (temp at null)
	not circular and returns false 
if (temp points first node)
	return true as its circular.
	}
	
function of datatype node newNode(data){

-To insert new nodes and link each one of them to the previous node by storing the address of the new node to the previous one.
-Then make them point to NULL.
}

In int main function

-First insert nodes for circular linked list and check its nature by calling isCircular function.
-Since it is true through if statement it prints "yes..
-Second insert a normal linked list and check its nature by calling isCircular function. As its not circular it prints "no",
...