[英]C++ Linked List insertion node and pointer in struct
我正在嘗試插入一些節點。 我的實現基於斯坦福教程。 http://cslibrary.stanford.edu/103/LinkedListBasics.pdf
以下是我的代碼。
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);
}
而我想做的是,我設置了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);
您也應該將Head移到當前節點!!!
當前,您的頭部指向具有數據1的節點。添加具有數據5的節點后,您的頭部仍位於具有數據1的節點上
您所做的其他添加都是無用的,它會導致您不知道的內存泄漏
看看Ross Bencina的答案,並將head = insert_node(head,5); 而不是只調用insert_node(head,5);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.