Simple linked list in Perl

This is the simplest linked link implementation I have yet to see. It takes more lines of code in C or Java. In Perl it is so straightforward:


#!/usr/bin/perl

# adapted from Mastering Algorithms in Perl
use strict;
use warnings;

my $squares = undef;

# we put the last element in the linked list first, then add to it.
foreach (reverse 1..5) {
	$squares = [ $squares, $_ * $_ ];
}

my $sq = $squares->[0][0][1];
print "3rd square: $sq\n";

$sq = $squares->[0][0][0][0][1];
print "5th square: $sq\n";

Exercise: post a singly linked list implementation in a language of your choice.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

Up ↑

%d bloggers like this: