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
In reply to Re: Reversing a singly linked list
by GrandFather
in thread Reversing a singly linked list
by punitpawar
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |