我一直在努力在C中實現鏈表,所以在有人喊我之前:是的,這是「家庭作業」。我一直在試圖解決和尼克Parlante的「鏈表基」工作 - 在免費提供:http://cslibrary.stanford.edu/103追加在鏈表的末尾
功能:在鏈表的末尾插入元素
我偶然在一個實現問題和管理構建一個解決方法:如果我在LList中使用「EndPointer」,我可以使用返回函數來設置函數的EndPointer,以交付新的ReferencePointer,然後在main中更改它。
碼 - 工作正常,但beeing解決方法:
// within main
lastPtrRef = _pushEnd(lastPtrRef, i);
// == function: push to end
node** _pushEnd(node **endRef, int value)
{
// 1) allocate stack mem/make room for new element
node *newNode = malloc(sizeof(node));
// do the data work
newNode->value = value;
// 2) make element point to NULL (fo beeing the new last element
newNode->next = NULL;
// 3) make old last element point to new element
*endRef = newNode;
return &(newNode->next); // more readable then vers. below
// this returns the mem address only of the pointer of the node!!!
//return (&((*endRef)->next));
}
============================== ================================================
這是我迄今爲止做的功能內的所有工作,但它實際上不起作用。任何提示,我沒有得到什麼?!
void _pushEnd(node **endRef, int value)
{
// 1) allocate stack mem/make room for new element
node *newNode = malloc(sizeof(node));
// do the data work
newNode->value = value;
// 2) make element point to NULL (fo beeing the new last element
newNode->next = NULL;
// 3) make old last element point to new element
*endRef = newNode;
}
莫非,那我真的需要一個指針引用指針的指針的內容,真正改變的最後一個元素(範圍:主),所以我目前似乎只有被修改局部變量「endRef」而不是它的內容?!
任何幫助,將不勝感激......
編輯: 的想法是不使用虛擬節點在LLIST的開始追加。
我的結構是這樣的:
typedef struct node {
int value;
struct node *next; } node;
主 - 本地變量(棧):
node *head = NULL;
node **lastPtrRef = &head;
編輯: 大多數命題結束了反正返回refPointer。但也許這不是一個壞主意,因爲它不會需要一個refPointer到refPointer。
Thx爲您的所有幫助和許多有用的評論!
,請告訴我們的結構(一個或多個) – 2013-02-23 11:39:04
標識符開始以下劃線後跟一個小寫字母被保留(用於實施?)。我建議你將下劃線從標識符的開始處移動到末尾:'_pushEnd' ==>'pushEnd_'(或者甚至可以全部省略下劃線) – pmg 2013-02-23 11:39:53
@pmg:「以下劃線開頭並帶有小寫字母的標識符被保留「 - 那是什麼意思? sry,我對編碼很陌生,開始用它來標記我自己的功能。 這樣就是不好的編碼風格? – LeTigre 2013-02-23 13:56:00