Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Perl linked list

by Laurent_R (Canon)
on Apr 01, 2015 at 17:55 UTC ( [id://1122176]=note: print w/replies, xml ) Need Help??


in reply to Perl linked list

As promised yesterday, this is my code to create a linked list and count its nodes:
use strict; use warnings; use Data::Dumper; my $pt = { value => "D", next => undef }; my $pt2 = {value => "C", next => $pt}; $pt = {value => "B", next => $pt2}; my $L = { value => "A", next => $pt}; sub solution { my $list = shift; my $length = 0; while (1) { return $length unless defined $list->{value}; # added for the +case of an empty list print $list->{value}; $length++; return $length unless defined $list->{next}; $list = $list->{next}; } } my $len = solution($L); print "\n$len \n"; print Dumper $L;
Which finds 4 nodes and prints this:
ABCD 4 $VAR1 = { 'next' => { 'next' => { 'next' => { 'next' => undef, 'value' => 'D' }, 'value' => 'C' }, 'value' => 'B' }, 'value' => 'A' };
As I said yesterday, the initialization of the list could be simpler, but perhaps less easy to understand for a relative beginner. But this is how I would probably code the initialization of the linked list:
my $L = { value => "A", next => { value => "B", next => { value => "C", next => { value => "D", next => undef, } } } };
Or, better (especially if there are more nodes), I would construct it in a loop:
my $L; for ( reverse qw / A B C D E F G/) { my $pt = { value => $_, next => $L }; $L = $pt; }
Which prints:
$ perl linked_list.pl ABCDEFG 7 $VAR1 = { 'next' => { 'next' => { 'next' => { 'next' => { 'next' => { +'next' => { + 'next' => undef, + 'value' => 'G' + }, +'value' => 'F' }, 'value' => ' +E' }, 'value' => 'D' }, 'value' => 'C' }, 'value' => 'B' }, 'value' => 'A' };

Je suis Charlie.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1122176]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2024-04-24 22:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found