我被分配了一項任務,即在 Perl 中使用給定的引數創建一個回圈鏈表,而不使用陣列或散列來存盤資料,只使用參考。結構中的第一個元素的值為 0,與用戶的輸入無關。它還應該支持使用“-”和“ ”遍歷當前選擇的元素。程式的輸出總是從預定義的元素開始,值為 0。所以結果應該是這樣的:
./task.pl 3 2 1
0 3 2 1
./task.pl A D - B C E
0 A B C D E
./task.pl A - B
0 B A
我想出的當前代碼是:
#!/usr/bin/perl
use strict;
use warnings;
my @elements = @ARGV;
my ($first, $last);
$first = { value => '0', 'prev' => $first, 'next' => $first };
my $pointer = \$first;
for (@elements) {
if ($_ == '-') {
} elsif ($_ == ' ') {
} else {
$_ = $pointer->{'next'};
$_ = { value => "$_", 'prev' => $pointer, 'next' => undef};
$pointer = \$_;
$last = $_;
}
}
我不確定如何進一步處理,也不能Class::Struct使用類似的匯入。
uj5u.com熱心網友回復:
首先,您使用的是哈希。{}創建一個哈希并回傳對它的參考。這是對的。哈希被用作結構/類,這不是分配希望您避免的。
其次,你有$firstand$last和一個虛假的初始元素。所有這些都是錯誤的。你只需要我的my $pointer;,雖然我會這樣稱呼它my $current;。
第三,您使用對標量 ( \$var) 的參考。這在這里沒有用。對回傳的哈希的參考就{}足夠了。
上代碼。有三個不同的組件:插入第一個元素,插入 和-列印構建的串列。
插入第一個元素
第一個論點很特別。它不能是 和-。其他插入總是在另一個元素之后插入,但第一次插入并非如此。
簡而言之,我們創建了一個串列,該串列完全由一個節點組成,節點的值為第一個元素。
我們曾經undef表示一個不存在的節點。
my $pointer = { value => shift(@elements), prev => undef, next => undef };
和-
并-更改當前節點(如 所示$pointer)。
如果 接收到,則要$pointer指向當前節點的prev欄位所指向的節點。
如果-接收到,則要$pointer指向當前節點的prev欄位所指向的節點。
您總是要問自己是否有特殊情況,并且每個 和 都有 一個-。可能會嘗試到達第一個 ( A - -) 之前的節點,也可能嘗試到達最后一個 ( A ) 之后的節點。die如果嘗試到達不存在的節點,您應該這樣做。
插入
$pointer我們總是在當前節點(一個參考)之后插入。
我們再次詢問自己是否有特殊情況(例如嘗試-在已經在第一個節點時使用)。但是沒有。$pointer將始終指向一個有效的節點。
在串列中插入一個節點后,我們要$pointer參考新創建/插入的節點。
列印串列
We want to print the entire list from start to end, so we will need to start by finding the start of the list. This is the same operation as - applied repeatedly until the first node is found. (The first node is the one which has no previous node.)
Then, it's just a question of traversing the list in the other direction (like does), printing the values as you go along.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/450447.html
上一篇:Perl:子程式不均勻/例外行為
