Write an algorithm that counts number of nodes in the circular linked list



Write an algorithm that counts number of nodes in the circular linked list..

Answer / Ashutosh Upadhyay

Here's an iterative solution for counting nodes in a circular linked list. Let `slow` and `fast` be pointers.n
1. Initialize `slow` to the head of the list, and `fast` to `NULL`.
2. Move `fast` two steps ahead of `slow` (i.e., `fast = slow->next->next`).
3. Continue moving `slow` one step ahead (i.e., `slow = slow->next`).
4. If `fast` and `slow` meet, the number of nodes in the circular linked list is one less than the number of steps taken by `slow` since they would have met at the starting node.
5. After step 4, move `slow` to the beginning of the list (i.e., `slow = head`) and increment a counter for each step taken until meeting the original position of `fast`.

Is This Answer Correct ?    0 Yes 0 No

Post New Answer

More Data Structures Interview Questions

What is mean by selection sort?

1 Answers  


Is set sorted?

1 Answers  


When will we get ArrayStoreException?

1 Answers  


Explain the Linked List

1 Answers   Tech Mahindra,


Differentiate between hashset and hashmap.

1 Answers  


What happens if we try to insert duplicate key in hashmap?

1 Answers  


Define adjacent nodes?

1 Answers  


Is a hash table a map?

1 Answers  


Can binary tree have 1 child?

1 Answers  


What is data and its type?

1 Answers  


What happens if we put a key object in a hashmap which exists?

1 Answers  


What is difference between data type and data structure?

1 Answers  


Categories