Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

Re: OOP/Linked List Question

by Grygonos (Chaplain)
on Feb 07, 2005 at 16:21 UTC ( #428720=note: print w/replies, xml ) Need Help??

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; }

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://428720]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (7)
As of 2018-05-24 16:25 GMT
Find Nodes?
    Voting Booth?