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};
}
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.