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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |