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:

use strict; use warnings; use Data::Dump; { package Node; sub new { my ($class, $value, $next) = @_; my $self = { data => $value, next => $next, }; return bless $self, $class; } } my $head = Node->new(2, undef); my $last = $head; $last = Node->new($_, $last) for reverse (4, 5, 4, 6, 2, 7, 8); $head->{next} = $last; my @elements; my $curr = $head; while (1) { print "data : $curr->{data}\n"; push @elements, $curr->{data}; last if ($curr->{next} == $head); $curr = $curr->{next}; } dd \@elements;

Output:

13:27 >perl 1535_SoPW.pl data : 2 data : 4 data : 5 data : 4 data : 6 data : 2 data : 7 data : 8 [2, 4, 5, 4, 6, 2, 7, 8] 13:27 >

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

Hope that helps,

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


In reply to Re: How to find all the elements in a circular linked list by Athanasius
in thread How to find all the elements in a circular linked list by punitpawar

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.