473,569 Members | 2,879 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Detection of a loop in a linked tree (or linked list)

mac
I found that with memory allocating techniques used nowadays
(addresses alignment, eg. on 32bit machines) one can detect loops in a
tree structure very fast, without using extra memory. This is due to a
possibility of storing extra information in unused bits of the tree
pointers (it works for linked lists too). One can say it is dangerous
or obvious, but I haven't seen it anywhere, and maybe it will be
useful for someone.

The procedure of loops detection has two steps:
1. Going through the tree with marking visited nodes (in pointers to
them) and checking if every node was visited only once (visiting node
twice means a loop)
2. Going through the tree once again and fixing tree pointers values,
to get the original tree structure
Below is an example code in C - you need only to add tree creation
function you like.

/*
* BEGINNING OF THE FILE
*/

#include "stdio.h"
#include "ctype.h"
#include "malloc.h"
#define LEAFS 2 //can be any integer >0

typedef struct t { //simple tree structure
int data;
struct t * leafs[LEAFS];
} tree;

/*
* test for cycles in a tree by using pointers reallignment
*/
int TestTreeAl(tree **root)
{
int i=0;
int j;
tree *p;
if (*root==NULL) return 0;
else
{
j=((int)(*root) )%2;
if (j!=0) return 1; //if a node is marked with odd pointer - cycle
detected
p=*root; //remember the correct pointer
(int)*root=((in t)*root)+1; //mark the node
for (i=0; i<LEAFS; i++) //visit all the leafs
if (TestTreeAl(&(p )->leafs[i])==1) return 1;
}
return 0;
}

/*
* fix allignment of tree pointers
*/
void FixTree(tree **root)
{ int i,j;
if (*root!=NULL)
{
j=(int)(*root)% 2;
if (j!=0)
(int)*root=((in t)*root)-1; //unmark previously marked node
for (i=0; i<LEAFS; i++)
{
if ((j!=0) && ((*root)->leafs[i]!=NULL))
FixTree(&((*roo t)->leafs[i]));
}
}
}

/*
* test linked tree for cycles
* returns 1 if any cycles were detectet, otherwise it returns 0
* (almost no additional memory used, only two visits in each tree
element)
*/
int TestTree(tree *root)
{
int i=TestTreeAl(&r oot); //testing for tree cycles with pointers
reallignment
FixTree(&root);
return i;
}

/*
* print all the data from the tree (sequence is not important)
*/
void print_tree_data (tree *root)
{
int i;
if (root!=NULL)
{
printf("%d\n",r oot->data);
for (i=0; i<LEAFS; i++)
print_tree_data (root->leafs[i]);
}
}

void main()
{
tree *root;
int i;

printf("* Example of a fast and memory efficient method \n* for
finding cycles in a tree structure (by Maciej Huk)\n\n");

root=NULL; //for NULL tree we will have no cycles
//make_tree(&root ); //You need to define this function yourself

print_tree_data (root); //if tree was OK, the print makes no problems

i=TestTree(root );

printf("Before adding the cycles: ");
if (i==0) printf("NO CYCLES :)\n");
else printf("CYCLES DETECTED!\n");

/*
* try adding cycles to your tree (beware for the initial tree
structure!)
*/
//root->leafs[1]->leafs[0]=root->leafs[0]->leafs[1]; //example of a
cycle to try
//root->leafs[0]->leafs[0]->leafs[0]=root; //...and another one

i=TestTree(root );

printf("\nAfter adding the cycles: ");
if (i==0) printf("NO CYCLES :)\n");
else printf("CYCLES DETECTED!\n");

if (i==0) print_tree_data (root); //if there is no cycles we can
easily print the tree

printf("\n\nPre ss any key to exit...");
while (!getch());
}

/*
* END OF THE FILE
*/

Best regards,
Maciej
Jun 27 '08 #1
0 2193

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
11448
by: Jani Yusef | last post by:
Based on an interview question I heard of but did not know the answer to....... How do you find and remove a loop from a singly linked list? In a google groups search I found the following code which will detect the loop but I am stumped how one would remove this loop. Any ideas? typedef enum { FALSE, TRUE } bool;
6
1112
by: JIM.H. | last post by:
Hello, How can I loop through the items in a dropwdown list: myDDL in C# to see if there is a string: “xyz”? Thanks, Jim.
5
3214
by: Allerdyce.John | last post by:
Hi, I have this piece of code which loops thru a STL list, but that causs an infinite loop. bool Executer::group(MyList& bl, ResultList & grl) { for (ExecuterList::iterator i = _executerList.begin(); i != _executerList.end(); i++) {
3
2754
by: rameshwar83 | last post by:
Suppose we have a linked list..... haviing loop..... suggest me some algo to remove loop from list..... Ex. A->B->C->D->E->F->G->H->I->E in this list node iI points to node E .... make this list like this... A->B->C->D->E->F->G->H->I->NULL ...
3
1527
by: sanjayuce | last post by:
Q: Plz send me the code for this question. How to check whether there exists any loop in a linked list. thanks. regards sanjay
2
3007
by: raven.mp4 | last post by:
Hi, I have a little question about std::list iterators. Take a look at this piece of code: list<Type*>::iterator it = myList.begin(); Type *p; for(it; it != myList.end(); ++it) {
2
2331
by: Rohit kumar Chandel | last post by:
How to find whether there is a loop in a linked list. suppose I have a linked list in the shape of numeral 9(next pointer of last node points to somewhere in the middle of list instead of pointing to NULL)
2
1291
by: msali36 | last post by:
Hi, i just want to know how can i display the parent- child information in hirarchy tree format in vb.net. for example : GrantParent parent parent
0
7930
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8138
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7681
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6290
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5228
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3662
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3651
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1229
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
950
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.