我目前正在学习指针和结构,而且我正在进行练习。 我的目标是编写一个函数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