2013-03-15 28 views
1

我想通過字符的字符串,使併爲它分配,性格,一個鏈表分配字符串鏈表,宣佈像這樣:問題在阿達

type lstring is private; 
type lstring_node; 
type lstring_access is access lstring_node; 
type lstring_node is 
    record 
     Char : character; 
     Position : integer; 
     Next : lstring_access; 
    end record; 

private 
    type lstring is 
     record 
      First : lstring_access := null; 
     end record; 

功能分配它是這樣的:

function toLstring (Input : string) return lstring is 
    LStr : lstring; 
    Current : lstring_access; 
begin 
    -- Set the first item of LStr as Current. 
    -- LStr will from now on inherit the items of Current. 
    LStr.First := new lstring_node; 
    Current := LStr.First; 

    -- Iterate through the string and add it to the lstring. 
    for I in 1..Input'Length loop 
     if I /= 1 then 
      Current := new lstring_node; 
     end if; 
     Current.Char := Input(I); 
     Ada.Text_IO.Put(Current.Char); 
     Current.Position := I; 
     Current := Current.Next; 
    end loop; 

    -- Return the new lstring. 
    return LStr; 
end toLstring; 

我知道通過調試,for循環工作得很好,並且元素被分配給Current就好了。但由於某些原因這些項目沒有被添加到LStr。我需要在for循環之後聲明一些東西來完成它嗎?我的印象是,因爲Current被分配給LStr.First,LStr會繼承附加列表的其餘部分。我錯了嗎?

感謝

+2

就像旁邊一樣,這是我遇到過的最令人震驚的自定義字符串類型。 – 2013-03-15 14:38:51

回答

3

在循環結束時,您分配Current.Next(這是空在這一點),以Current。這是一個價值副本。在下一次迭代中更改Current的值不會更改之前節點中的Next的值。 (心說Current.CharCurrent.Next是將實際做Current.all.Char/Next隱含的指針引用,但Current := new lstring_node不是解引用,因爲它改變了參考價值。)

相反,你應該分配new lstring_nodeNext,然後推動你Current參考:

for I in Input'Range loop 
    Current.Char := Input(I); 
    Ada.Text_IO.Put(Current.Char); 
    Current.Position := I - Input'First + 1; 
    if I /= Input'Last then 
     Current.Next := new lstring_node; 
     Current := Current.Next; 
    end if; 
end loop; 

注意,我改變了循環範圍(字符串不會在1啓動所必需的),並調整了位置計算,所以你會在你的名單基於1位指數結束了。

+0

啊謝謝你!完美的作品。沒有這樣想過。 – chazbot7 2013-03-15 21:02:16