Write a duty detectAndCountLoop() that checks whether a given attached List consists of loop and also if loop is existing then returns count of nodes in loop. For example, the loop is current in below-linked list and length the the loop is 4. If the loop is no present, climate the function should return 0.

You are watching: Iterate through linked list c++


Approach: it is well-known that Floyd’s cycle detection algorithm terminates when fast and slow pointers fulfill at a typical point. The is also known that this common point is among the loop nodes. Keep the address of this common allude in a tip variable to speak (ptr). Then initialize a respond to with 1 and start from the common allude and keeps on visiting the next node and increasing the counter till the typical pointer is reached again.At that point, the value of the counter will be same to the length of the loop.Algorithm:


Find the common point in the loop by using the Floyd’s bike detection algorithmStore the tip in a temporary variable and also keep a counting = 0Traverse the attached list until the same node is reached again and increase the counting while moving to following node.Print the count as size of loop
Output :4Complexity Analysis:Time complexity:O(n).Only one traversal the the connected list is needed.Auxiliary Space:O(1).As no extra room is required.

See more: Song That Might Play When Fighting Sans, Song That Might Play When You Fight Sans

Related Articles:Detect loop in a linked listDetect and Remove Loop in a linked ListThis short article is added by Shubham Gupta. If you like doyourpartparks.org and would like to contribute, friend can additionally write an write-up using write.doyourpartparks.org or mail your post to review-team
doyourpartparks.org. See your article appearing on the doyourpartparks.org main page and help other Geeks.Please compose comments if you discover anything incorrect, or you desire to share more information around the topic debated above.


https://media.doyourpartparks.org/auth/avatar.png
subtleseekerinderDuMCAPriyaBadchariyaLeonardo_Da_VinciRajput-JiSHUBHAMSINGH10andrew1234GauravRajput1sweetytysimranarora5sos
Doubly attached List | collection 1 (Introduction and also Insertion)LinkedList in JavaImplement a stack using singly attached listLinked list vs ArrayQueue - connected List Implementation
Merge 2 sorted linked listsDelete a connected List node at a given positionImplementing a attached List in Java utilizing ClassFind size of a linked List (Iterative and also Recursive)Circular connected List | set 1 (Introduction and also Applications)
We use cookies to ensure you have actually the finest browsing suffer on our website. By making use of our site, youacknowledge the you have actually read and understood ourCookie plan & Privacy PolicyGot that !