我目前正在學習指針和結構,而且我正在進行練習。 我的目標是編寫一個函數head_insert,它基本上創建一個新的列表元素,並將其附加到前面。在C++中創建列表
注意:我知道C++中已經有了一個數據類型列表,但這只是爲了更好地行使和理解動態結構背後的概念。
我的代碼如下:
struct list{
int val;
list *next = NULL;
};
typedef list* ptr_list;
ptr_list head_insert(ptr_list head, const int element){
ptr_list tmp_head;
tmp_head = new list;
tmp_head->val = element;
tmp_head->next = head;
return tmp_head;
}
int main(){
ptr_list head = NULL;
head = head_insert(head, 1); // This is the crucial step I think, as head is not initialized yet
head = head_insert(head, 2);
return 0;
}
的事情是,我想要的功能head_insert也上班的時候頭是空的,即我的列表是空的。但是,在調試我的代碼時,我注意到在head_insert頭的每次調用都保持爲NULL之後,會發生head(head-> val,head-> next)內的更改。
這是爲什麼?這與tmp_head的範圍有關嗎? 我怎麼能修改我的代碼以我想要的方式工作?
如果我不套頭在開始NULL,但手動分配空間並設置它的第一要素,一切工作完全正常:
head = new list;
head->val = 1;
感謝您的時間和幫助! 乾杯
我沒有看到問題。 '頭'似乎在變化:http://coliru.stacked-crooked.com/a/baf503d3389a8cac –
代碼看起來很正常。也許你在調試器時遇到了一些問題。 – arturx64