所以我知道在Stack overflow上有上百个例子,实际上我已经使用了那里的所有信息-所以这就是我所拥有的
use strict;
use warnings;
use Data::Dumper;
my $head= undef;
my $tail=\$head;
open FILE, "<datastored.txt" or die $!;
while (<FILE>){
my $node = {
"data" => $_ ,
"next" => undef
};
$$tail=$node;
$tail = \$node->{"next"};
};
print Dumper $head; #before reversing
$head = reverse_list($head);
print Dumper $head; #after reversing
sub reverse_list{
my ($list) =@_[0];
my $previous = undef;
while ($list->{next}){
$forward = $list->{next};
$list->{next}= $previous;
$previous = $list;
$list=$forward;
};
return $previous;
};这是我得到的输出
#this is the output before reversing (normal linked list)
$VAR1 = {
'next' => {
'next' => {
'next' => {
'next' => undef,
'data' => 'line 4
'
},
'data' => 'line 3
'
},
'data' => 'line 2
'
},
'data' => 'line 1
'
};
#this is the linked list after reversing (WITHOUT THE LAST DATA VARIABLE - "line 4")
$VAR1 = {
'next' => {
'next' => {
'next' => undef,
'data' => 'line 1
'
},
'data' => 'line 2
'
},
'data' => 'line 3
'
};注意--文件datastored.txt的内容只是
line 1
line 2
line 3
line 4因此,我的问题是,数据“第4行”到哪里去了?我应该做些什么更改才能真正反转链表而不丢失任何值。
发布于 2012-06-10 09:16:49
您的反转子例程几乎是正确的。但是,由于您使用的条件,它会遗漏最后一个条目(即将其添加到最终的反转列表中)。您有两个选择:
while ($list->{next})更改为while ($list)并使代码更加得体。while循环的末尾添加一个$list->{next}= $previous;,以将最后一个剩余节点添加回反转列表中。(想一想两个元素的列表,看看你的代码是做什么的)。https://stackoverflow.com/questions/10965712
复制相似问题