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.

In reply to Re: Perl linked list by Laurent_R
in thread Perl linked list by Perl_is_Perl

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.