Skip to content

Instantly share code, notes, and snippets.

@esobchenko
Created September 9, 2009 12:22
Show Gist options
  • Save esobchenko/183677 to your computer and use it in GitHub Desktop.
Save esobchenko/183677 to your computer and use it in GitHub Desktop.
single linked list reverse function
#!/usr/bin/perl
# by Eugen Sobchenko, esobchenko@gmail.com
use strict;
use warnings;
use Data::Dumper;
sub reverse_list {
my ($previous, $current) = @_;
my $next = $current->{n};
$current->{n} = $previous;
if ($next eq 'null') {
return $current;
}
return reverse_list($current, $next);
}
my $head = { v => 1, n => { v => 2, n => { v => 3, n => 'null' } } };
print "before:\n";
print Dumper( $head );
my $new_head = reverse_list('null', $head);
print "after:\n";
print Dumper( $new_head );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment