Posted By

freephys on 12/02/09

Statistics

Viewed 498 times
Favorited by 0 user(s)

Example of circular data structure : Network class

/ Published in: Perl
`##1#Network class relies on two other classes#1.Node class#2.Link, whose objects represent a single unidirectional link to another Node##package Network;use strict;sub new{my (\$class) = @_;bless { _nodes => [] }, \$class;}sub node{my (\$self, \$index) = @_;return \$self->{_nodes}->[\$index];}sub add_node{my (\$self) = @_;push @{\$self->{_nodes}}, Node->new();}###providing the Network class with a destructor that explicitly removes the Links#between Nodes at the appropriate time##sub DESTROY{my (\$self) = @_;foreach my \$node ( @{\$self->{_nodes}} ){\$node->delete_links();}} ##2# Node class, which Network class is relied on##package Node;use strict;{my \$_nodecount=0;sub _nextid { return ++\$_nodecount }}sub new{my (\$class) = @_;bless { _id => _nextid(), _outlinks => [] }, \$class;}sub add_link_to{my (\$self, \$target) = @_;push @{\$self->{_outlinks}}, Link->new(\$target)}###in order to remove circular data structure##sub delete_links{my (\$self) = @_;delete \$self->{_outlinks};}##3#Link class which Node class is relied on##package Link;use strict;{my \$_linkcount=0;sub _nextid { return ++\$_linkcount }}sub new{my (\$class) = @_;bless{_id=> _nextid(),_to=> \$_[1],}, \$class;}`