http://www.perlmonks.org?node_id=428720


in reply to OOP/Linked List Question

The following structure implements a two node circularly linked list... you can extend it as far as you want.. you still need to create the methods to add something to it, and delete something from it. the id number is the array position, the name is the data key of the hash.. and the next key is the reference to the next node.

warning.. code contains infinite loop to demonstrate that what is considered to be the current node is changing
use strict; use warnings; my $ll = [ {data=> 'x', next=> 1}, {data=> 'y', next=> 0}]; my $item = $ll->[0]; while(1) { print $item->{data}."\n"; $item = $ll->[$item->{next}]; }

update addItem adds an item to the end of the list.. causing whatever pointed to the beginning of the list to now point to the new item and making the new item point to the beginning of the list.

use strict; use warnings; use Data::Dumper; my $ll = [ {data=> 'x', next=> 1}, {data=> 'y', next=> 0}]; my $data = 'z'; addItem($ll,\$data); print Dumper($ll); sub addItem { my ($ll,$item) = @_; foreach(@{$ll}) { $_->{next} = @{$ll} if $_->{next} == 0; } $ll->[@{$ll}] = {data=>$$item, next=>0}; return; }