What you'll want to do is read Mastering Algorithms With Perl by Jon Orwant et al. Then indeed you'll be able to do what you want to do.

At the risk of giving away information too easily (and thus reducing the likelihood of enlightenment), here's an untested, off-the-top-of-my-head example of doing linked lists in Perl:

A linked list node is just a data structure with one slot for data and one slot pointing to another node. So you could use an anonymous array, like so:

## ## make_node() ## Arguments: $value: scalar, contents of the node ## $next_node: linked list node (optional) ## sub new_node { my ($value, $next_node) = @_; my $new_node = [$value, $next_node]; return $new_node; }

Okay, okay, so that would build the node backwards, but hey. Then, you could build an entire list by doing this:

$last_node = new_node('last', undef); $middle_node = new_node('middle', $last_node); $first_node = new_node('first', $middle_node);

You could traverse this list like so:

sub traverse_nodes { my ($node) = @_; my ($value, $next_node) = @$node; if ( defined($next_node) ) { return ($value, traverse_nodes($next_node)); } else { return $value; } }

At least I think that'll work. Somebody speak up if I'm smoking something. Then:

print join(' ', traverse_nodes($first_node) ), "\n";
should print "first, middle, last".

stephen


In reply to Re: Linked List by stephen
in thread Linked List by Anonymous Monk

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.