2012-04-02 101 views
0

隨意編輯標題,engrish有時會混淆而不是幫助。創建指針的指針並進行修改而不修改原始指針?

我必須使(和不,我不能改變,這是它的方式必須是)簡單的鏈接列表。 否我不能使用STL或std :: list。大部分工作都是在紙上完成的,但我似乎遇到了實現非常基本的光標的問題。

這是列表中的我的節點(的一部分):

struct Node { 
    int ap_nr; 
    Node *next; 
}; 

我想要走線槽我添加節點功能列表:

void add_node (Node **begin, int ap_nr) 
{ 
    stuff happens 
} 

這是我如何調用函數:

add_node(&(*begin), ap_nr); 

我想要創建一個從開始(我的列表的頭)開始的光標,並通過每個節點我們槽荷蘭國際集團cursor->next直到我到達終點(while (cursor->next!=0))

,但我不能簡單地說:

Node *cursor; 
cursor = new Node; 
cursor = begin; 

因爲這將直接覆蓋光標首先,讓我嘗試無效。我仍然需要做一個指針才能開始並能夠調用STRUCT函數「 - > next」

我該怎麼做?

*還*我該如何記住以前的節點?我可以這樣做:

Node *previous; 
previous = new Node; 
previous = &(*begin); // ? 
+1

'&(* begin)'完全等同於'begin',那麼爲什麼不在調用add_node時使用那個呢? – celtschk 2012-04-02 17:33:40

+0

首先,在C++的英文討論中通常使用「迭代器」,而不是「遊標」。其次,你不提供太多的信息。你是說你想使用一個Node結構*作爲一個迭代器,並且也是一個數據容器? – 2012-04-02 17:34:41

+0

每個節點都是獨立的......它擁有它需要的所有信息,我需要做的唯一修改是添加一個或刪除一個(暫時)。我想要一種從一個節點轉到另一個節點的方式(列表不過是鏈接節點),直到我達到我的目標(無所謂),而不會丟失我的第一個節點。我也試過簡單的'開始',但它沒有工作,'&(*開始)'工作,所以我沒有改變。 – Kalec 2012-04-02 17:38:16

回答

1

這聽起來像你想穿越在add_node功能列表。如果是的話請嘗試以下

void add_node (Node **ppBegin, int ap_nr) 
{ 
    if (!ppBegin) { 
    // Need to handle the case of bad user data here 
    } 

    // Traverse until we get the to the empty next value 
    while ((*ppBegin)->next) { 
    ppBegin = &((*ppBegin)->next); 
    } 

    // ppBegin now points to the address of where the new node should go 
    Node* created = new Node(); 
    created->ap_nr = ap_nr; 
    *ppBegin = created; 
} 

注意:要開始調用這個函數,你應該只是add_node(&theListPointer)調用它。

+0

等待,不會'ppBegin =&((* ppBegin) - >下一個);'移動我的開始,從而使我失去我的列表的「頭」? – Kalec 2012-04-02 17:35:19

+0

@Kalec不,它不會。 C是一種傳值語言,因此'ppBegin'實際上是提供給它的值的副本。對列表的修改只有在你使用'* ppBegin = created'行的間接級別時纔會被調用者看到。在這裏,我通過複製挖掘並達到了變異的真實共享值 – JaredPar 2012-04-02 17:40:44

+0

和'* ppBegin = created;'?我不應該以某種方式將它鏈接到列表嗎?因爲列表是一個鏈接節點的簡單鏈,而不是實際的實體。什麼是「創造」? – Kalec 2012-04-02 17:42:14