in reply to Reversing a singly linked list

Why? In Perl you can use an array to efficiently insert and remove elements from anywhere in a list and trivially reverse it if you wish. In fact the easiest way to handle your problem is to convert between a Perl list and a linked list:

use strict; use warnings; use Data::Dumper; my $forwardList = buildList(1 .. 4); my $reverseList = buildList(reverse getList($forwardList)); print join (', ', getList($forwardList)), "\n";; print join (', ', getList($reverseList)), "\n";; sub buildList { my @elements = @_; my $head = {data => undef, next => undef}; my $next = $head; for my $element (@elements) { $next->{data} = $element; $next->{next} = {data => undef, next => undef}; $next = $next->{next}; } return $head; } sub getList { my ($head) = @_; my @data; while ($head) { last if !defined $head->{next}; push @data, $head->{data}; $head = $head->{next}; } return @data; }

Prints:

1, 2, 3, 4 4, 3, 2, 1
Premature optimization is the root of all job security

Replies are listed 'Best First'.
Re^2: Reversing a singly linked list
by NetWallah (Canon) on Feb 15, 2016 at 05:35 UTC
    Slightly shorter code (slow night):
    use strict; use warnings; use Data::Dumper; my $forwardList = buildList(1 .. 4); my $reverseList = buildList(reverse getList($forwardList)); print join (', ', getList($forwardList)), "\n";; print join (', ', getList($reverseList)), "\n";; sub buildList { my ($head, $node); for (@_){ $node = add_node($node,$_); $head ||= $node; } return $head; } sub add_node{ my ($prev, $data) = @_; return $prev->{next} ={data=>$data, next=>undef}; } sub getList { my ($head) = @_; my @data = ($head->{data}); while ( $head = $head->{next}) { push @data, $head->{data}; } return @data; }
    (The last node points to undef .. there is no empty node)

            "Think of how stupid the average person is, and realize half of them are stupider than that." - George Carlin