为什么这个简单的insert_back代码链表无法正常工作? [英] Whys is this simple insert_back code for linked list not working fine?

查看:81
本文介绍了为什么这个简单的insert_back代码链表无法正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了这个函数,用于在链表前插入一个节点。据我说这个代码应该可以工作,但不是。



I had written this function for inserting aa node at front of linked list. According to me this code should work but its not.

struct node* insert_back(struct node*& head, int data){
	struct node* p = head;
	while(p!= NULL){
		p = p->next;
	}
	struct node* new_node = (struct node*)malloc(sizeof(node));
	new_node->data = data;
	new_node->next = NULL;
	p  = new_node;
	return head;
}

推荐答案

您的代码创建一个新节点,设置 p 指向它,但不在任何地方将其添加到列表中。然后将 head 返回给调用者,此时 p 超出范围并丢失。您可以使用调试器逐步执行代码来轻松验证这一点。
Your code creates a new node, setting p to point to it, but not adding it into the list anywhere. You then return head to the caller, at which point p goes out of scope and is lost. You can verify this quite easily by using the debugger to step through the code.


这篇关于为什么这个简单的insert_back代码链表无法正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆