在链接列表前面添加节点 [英] Adding node in front of linklist

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

问题描述

我已经实现了以下链接列表,

I have implemented linklist as below,

struct node
{
    int data;
    node* next;
};

void initNode(node* head, int data)
{
    head->data = data;
    head->next = NULL;
}

void addNode(node* linkList, int data)
{
    node* newnode = new node;
    newnode->data = data;
    newnode->next = NULL;

    while (linkList)
    {
        if (linkList->next == NULL)
        {
            linkList->next = newnode;
            return;
        }
        linkList = linkList->next;
    }
}

void insertFrontNode(node* linkList, int data)
{
    node* newnode = new node;
    newnode->data = data;
    newnode->next = linkList;
    linkList = newnode;
}

void DisplayLinkList(struct node* linkList)
{
    int i = 1;
    while (linkList)
    {
        cout << "Linklist(" << i << ") " << linkList->data << endl;
        linkList = linkList->next;
        i++;
    }
}


int main()
{
    node* linkList  =new node;
    initNode(linkList, 5);
    addNode(linkList, 10);
    addNode(linkList, 30);
    insertFrontNode(linkList, 12);  
    DisplayLinkList(linkList);


    cin.get();
    return 0;
}

我的问题是,当我在initNode中初始化链接列表或在addNode中添加节点时,更改反映在我通过参数传递的linkst指针中。但是,如果我要在insertFrontNode中添加节点infront,则更改不会反映在链接列表指针中。

My question is, when i initialise linklist in initNode or add node in addNode, the changes are reflected in linkst pointer which i am passing thru argument. but If i am adding node infront in insertFrontNode, changes are not reflecting in the linklist pointer.

为什么?

推荐答案

您做得很好。您正在修改链接列表的标题,但未将其更新为因此,当您调用DisplayLinkList时,它是使用旧的头指针调用的,这就是为什么更改未反映出来的原因。检查以下代码:

You are doing fine.You are modifying the head of your linked list but not updating it to your outer world.So when you are calling DisplayLinkList it is called with the old head pointer which is why the changes are not reflecting. Check the below code:

void insertFrontNode(node** linkList, int data)
{
    node* newnode = new node;
    newnode->data = data;
    newnode->next = *linkList;
    *linkList = newnode;
}

int main()
{
    node* linkList = new node;
    initNode(linkList, 5);
    addNode(linkList, 10);
    addNode(linkList, 30);
    insertFrontNode(&linkList, 12);
    DisplayLinkList(linkList);


    cin.get();
    return 0;
}

以上代码,不仅在最前面添加了节点,而且更新了最前面的节点指针,以便显示函数获得新的更新的头部指针。

Above code,not only add the node at the front but also updates the head pointer such that display functions get the new updated head pointer.

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

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