所以我知道有数百个关于堆栈溢出的例子,事实上我已经使用了那里的所有信息 - 所以这就是我所拥有的
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 行”在哪里消失了,我应该改变什么才能真正反转链接列表而不会丢失任何价值。