1.snippet to reverse a linked list:
void reverse ( struct node **x )
{
struct node *q, *r, *s ;
q = *x ;
r = NULL ;
/* traverse the entire linked list */
while ( q != NULL )
{
s = r ;
r = q ;
q = q -> link ;
r -> link = s ;
}
*x = r ;
}
2.code to detect a loop in a linked list.
typedef struct node
{
void *data;
struct node *next;
}mynode;
mynode * find_loop(NODE * head)
{
mynode *current = head;
while(current->next != NULL)
{
mynode *temp = head;
while(temp->next != NULL && temp != current)
{
if(current->next == temp)
{
printf("\nFound a loop.");
return current;
}
temp = temp->next;
}
current = current->next;
}
return NULL;
}
No comments:
Post a Comment