C++ C++;结构中的链表插入节点和指针
我正在尝试插入一些节点。我的实现基于斯坦福教程 下面是我的代码C++ C++;结构中的链表插入节点和指针,c++,pointers,linked-list,new-operator,nodes,C++,Pointers,Linked List,New Operator,Nodes,我正在尝试插入一些节点。我的实现基于斯坦福教程 下面是我的代码 struct node { int p_data; struct node* p_next; node(node* head, int data) { p_next = head; p_data = data; } explicit node(int data) {
struct node
{
int p_data;
struct node* p_next;
node(node* head, int data)
{
p_next = head;
p_data = data;
}
explicit node(int data)
{
p_next = nullptr;
p_data = data;
}
}
这是我的插入函数
node* insert_node(node* head, int data)
{
return new node(head, data);
}
我想做的是,我为initial设置了1,2,3的列表,并想添加更多的元素,比如5,6,7。下面是我的尝试,但插入没有任何作用。所以我只打印出1,2,3。在主要功能中,我有
struct node* head = new node(NULL);
struct node* nodep_01 = new node(NULL);
struct node* nodep_02 = new node(NULL);
head->p_data = 1;
head->p_next = nodep_01;
nodep_01->p_data = 2;
nodep_01->p_next = nodep_02;
nodep_02->p_data = 3;
nodep_02->p_next = nullptr;
如果我打印这个,我得到1,2,3。然后我尝试再插入一个值为5的元素,但它没有任何作用
insert_node(head, 5);
谁能帮我做这个?我想在此列表中插入元素。。。提前谢谢
insert_node(head, 5);
应该是:
head = insert_node(head, 5);
你也应该将头部移动到当前节点 当前,您的头部指向数据为1的节点 添加数据为5的节点后,头部仍然位于数据为1的节点 您进一步添加的内容是无用的,它会导致您不知道的内存泄漏
查看Ross Bencina的答案,并将head=插入节点(head,5);而不是只调用insert_节点(head,5) 您可能还对我的链表变体调查感兴趣: