Showing posts with label Circularly linked list. Show all posts
Showing posts with label Circularly linked list. Show all posts

Tuesday, September 29, 2015

Circularly Linked List

Circularly linked list is a linked list where all nodes are connected to form a circle.There is no end or rear or null pointer.



Circularly Linked List

Circular linked list can be implemented in both singly linked list as well as doubly linked list.
The only difference between implementation of a circularly linked list and other linked list is that, Circularly linked list doesn't have a last element instead points to the head.Whereas other linked list points to null in place of the head.

To traverse through all the elements in the circularly linked list, we need to use two loops 
  1. One which checks the condition that the head reference is not equal to null
  2. Other loop which checks if the loop doesn't repeat. i.e temp variable doesn't equal to head.

Function to push an element into the Circularly linked list 





Source: Geeksforgeeks
Also Refer to Tortoise-Hare Algorithm

Thursday, September 24, 2015

Tortoise & Hare Algorithm

Tortoise & Hare algorithm is also known as Floyd's Cycle-Finding Algorithm.This is a technique for detecting infinite loops inside a linked list, symlinks, state machines etc.

To detect a loop inside a linked list
Source
  • Make a pointer to start of the linked list and call it Hare 
  • Make a pointer to the head of the linked list and call it Tortoise 
  • advance the Hare by two and the tortoise by one for every interation.
  • There's a loop if the Tortoise and Hare meet
  • There's no loop if the Hare reaches the end.
Algorithm is intersting as it takes O(n) time and O(1) space.

Python code to understand Tortoise and Hare algorithms
Source




With this Algorithm we detect the loops and iterations in a circularly linked list as suggested by the name Floyd's Cycle-finding Algorithm.

More Reference: Coding Freak