添加新节点到链表的新方法 [英] New approach for adding a new Node to a Linked List

查看:185
本文介绍了添加新节点到链表的新方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

void addNewNode (struct node *head, int n)
{
    struct node* temp = (struct node*) malloc(sizeof(struct node));
    temp -> data = n;
    temp -> link = head;
    head = temp;
}

在code给上面是一个函数的普遍错误版本在链表头添加一个新的节点。
一般来说,正确的版本一样,

The code give above is the popularly wrong version of a function for adding a new node at the head of a linked list. Generally the correct versions are like,

void addNewNode (struct node **head, int n);
void addNewNode (struct node * &head, int n);

我制定了另一个但其工作罚款的目的简单的功能。

I worked out another but simple function for the purpose which worked fine.

struct node* addNewNode (struct node *head, int n)
{
    struct node* temp = (struct node*) malloc(sizeof(struct node));
    temp -> data = n;
    temp -> link = head;
    return temp;
}

但我还没有看到这个被使用或code和辅导讨论,因此我很想知道,如果这种方法有一定的缺陷。

But I haven't seen this being used or discussed in code and tutorials and thus I am curious to know if this approach has some flaw.

推荐答案

该缺陷是,你依靠来电者进行头指针更新到列表中的最后一步。

The flaw is that you're relying on the caller to perform the last step of updating the head pointer to the list.

如果来电者忽略这样做,编译器不会抱怨,并为所有意图和目的列表中会出现不会改变(你会泄露已经为节点的内存)。

If the caller neglects to do this, the compiler will not complain, and for all intents and purposes the list will appear to not have changed (and you'll have leaked the memory for a node).

这篇关于添加新节点到链表的新方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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