Let me make a tiny change so that I can talk about this more easily. The problem is that one $list is being changed while the other $list isn't. So lets rename one of them:
The problem is that $list is updated when you modify $$lastnode, but my ($root, $lastnode) = @_; makes $root a copy of $list and so $root is not changed. Then add() returns $root and, in effect, you end up doing $list= $root, which restores $list to its previous value.use strict; my $list = { head=>undef, tail=>undef }; while (1) { print '<i>nput, <o>utput : '; chomp (my $input = <STDIN>); if ($input eq 'i') { add($list); next; } if ($input eq 'o') { show($list); next; } } sub add { my ($list) = @_; chomp (my $input = <STDIN>); my $newnode = [undef, $input]; $list{tail}[0]= $newnode; $list{tail}= $newnode; }
You could change the last line of add() to be return ($_[0], $lastnode); since $_[0] is an alias to $list and not a copy of $list.
But better would be to encapsulate the $list and $lastnode variables into a single item that is passed to add() and show().
- tye (but my friends call me "Tye")In reply to (tye)Re: Linked List Strangeness
by tye
in thread Linked List Strangeness
by Mandor
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |