This is/was an interview question I got two weeks ago.
Find where the loop begins in simple linked list.
I hope this figure will help understand what I mean :
[LEFT][1] ->[2] ->[3] ->[4] ->[5]
^ |
| U
[10] [6]
^ |
| U
[9]<- [8]<- [7][/LEFT]
If not the figure take a look at this where I make the error.
[LEFT]int main(void)
[LEFT]{
struct list
{
int val;
struct list *pnext;
} *phead, *plast, *pptr, *ploop, **pptmp, *p1, *p2;
int i;
phead = NULL;
pptmp = &phead;
for ( i = 1 ; i <= 10 ; ++i )
{
plast = (*pptmp) = malloc(sizeof(*phead)) ;
(*pptmp)->val = i;
(*pptmp)->pnext = NULL;
if ( i == 3 )
ploop = (*pptmp);
pptmp = &(*pptmp)->pnext;
}[/LEFT]
[LEFT]/* Doing the error !!!!!!!!!! */
plast->pnext = ploop;[/LEFT]
[LEFT]/* Trying to find the error. e.g. cell 10 */
/* Not its value of course but its address */
getchar();
return(0);
}[/LEFT]
[/LEFT]
My solutions :
1) If we have a filed in the struct which his value
is known to us. We can loop throw the list checking
if it is the value known to us, else chaning it to something else.
When we encounter the changed value, the previous cell
is the beging of the loop.
2) Allocating an array of pointers. Looping throw the list
and adding its address to the array. Every time we had
a new address we check if it is not in the array.
If it is in the array the previous cell is the beging
of the loop.
Anybody has other solutions ?
Thanks in advance.