punitpawar has asked for the wisdom of the Perl Monks concerning the following question:

Hello , I wanted to know if there is a way in perl to iterate a circular linked list and capture all the elements in it .
so if I have a list like 2->4->5->4->6->2->7->8->2 , where after 8 it points back to the head 2 . Is thee a way in which I can iterate through this list and push the elements in an array ?
I tried something like this below , but this does not seem to work. Any advise on how this can be solved ?
Consider that the each node in the linked list is having the following data structure
$head ={ data=>2 next=>undef; ## or the next node to which it is linked to }
my @elements; my $curr=$head; ## I am trying to make my curr pointer start from t +he head while (1){ last unless ($curr->{next} == $head); # here I am trying to +check that the next element is not head. And if is then break out of +the loop print "data : $curr->{data} \n"; push(@elements,$curr->{data}); $curr = $curr->{next}; }

Replies are listed 'Best First'.
Re: How to find all the elements in a circular linked list
by Athanasius (Archbishop) on Feb 10, 2016 at 03:32 UTC

    Hello punitpawar,

    The problem is with this line:

    last unless ($curr->{next} == $head);

    First, the logic is back-to-front: you want to break out of the loop when $curr->{data} is equal to $head, so you need if, not unless.

    Second, that test comes too soon. If you break out of the loop when the next node is $head, you will fail to push the last value onto @elements. So you need to move the test to follow the push statement:

    You should also consider using a dedicated module, such as Data::CircularList.

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Re: How to find all the elements in a circular linked list
by GrandFather (Saint) on Feb 10, 2016 at 01:05 UTC

    Show us the real data structure that would contain the sample data you provided. Also (and maybe more importantly), tell us why you need a circular linked list. Perl's arrays and array handling mean that most things you might use lists for in other languages are easy and efficient using a Perl array.

    Premature optimization is the root of all job security