不使用Node**在链表头部插入节点的问题求助
问题原因与解决方法
你的insert函数逻辑本身没问题,但调用时没有接收函数返回的新头结点,导致外部的head变量根本没更新。
在C++里,传递Node*属于值传递——函数里的head是外部head的副本,你在函数里把副本指向新节点,不会改变外部原来的head的指向。
解决步骤
只需要在main里调用insert时,把返回值赋值给原head变量:
head = insert(head, 4);
修改后的完整代码示例
#include <iostream> using namespace std; struct Node { int data; Node* next; }; Node* insert(Node* head, int newval) { Node* newnode = new Node; newnode->data = newval; newnode->next = head; head = newnode; return head; } int main() { Node* head = new Node; Node* two = new Node; Node* three = new Node; head->data = 1; head->next = two; two->data = 2; two->next = three; three->data = 3; three->next = NULL; // 接收返回的新头结点,更新原head head = insert(head, 4); // 遍历验证结果 Node* curr = head; while(curr != NULL) { cout << curr->data; curr = curr->next; } cout << endl; // 记得释放内存,避免泄漏 curr = head; while(curr != NULL) { Node* temp = curr; curr = curr->next; delete temp; } return 0; }
这样修改后,外部的head就会指向新插入的节点4,遍历链表就能得到预期的4123。
内容的提问来源于stack exchange,提问作者Lindsay Forras
相关产品推荐
相关产品推荐

