关于链表,C ++的问题 [英] question about Linked List, C++

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

问题描述

嘿,我有一个小问题.

我已经编写了此函数,该函数应该在链表的开头插入一个元素.

Hey guys, I have a small question.

I''ve written this function that is supposed to insert an element at the beginning of the linked list.

void insertAtStart(node* head /* pointer to head of the list*/, int data /* value of the new node that is to be inserted*/)
{
    /* perform insertion */

    node* temp = new node; // create a temporary node
    temp->next=head; // make this new node point where the head of the list was pointing previously
    temp->data=data; // update value of the temporary node
    head=temp; // make head pointer point to this newly inserted node
}



当我想调用上面的函数时,我的问题就开始了:



My problems start when I want to invoke above function:

insertAtStart(head,9000);


问题是,当我调试时,调用


The thing is when I debug, the address where the "head" is pointing before and after invocation of the

insertAtStart 

函数前后的头"所指向的地址保持不变.

因此,基本上什么都没有改变.是因为一旦调用insertAtStart函数,"temp"节点就被破坏了?或必须在某个地方全局声明"head"-如果是,为什么? (为什么当前的解决方案不起作用?).

function remains the same.

Thus basically nothing gets changed. Is it because "temp" node gets destroyed once the insertAtStart function has been called? or the "head" must be declared globally somewhere - if yes, why? (and why isn''t current solution working?).

Thanks!

推荐答案

将您的代码更改为以下形式:
Alter your code to something like this:
void insertAtStart(node** head /* pointer to pointer to head of the list*/, int data /* value of the new node that is to be inserted*/)
{
    if(head == nullptr)
    {
      // Do somthing to indicate that you forgot to pass a valid pointer
    }
    /* perform insertion */
 
    node* temp = new node; // create a temporary node
    temp->next=*head; // make this new node point where the head of the list was pointing previously
    temp->data=data; // update value of the temporary node
    *head=temp; // make head pointer point to this newly inserted node
}



您可以这样使用:



Which you can use like this:

node *head = nullptr;
insertAtStart(&head,8000);
insertAtStart(&head,9000);



最好的问候
Espen Harlinn



Best regards
Espen Harlinn


收件人:Espen Harlinn

这看起来很整洁,我会尝试一下.但是,为什么我的解决方案不起作用?实际上,我已经注意到,如果我只是尝试更改函数中指针所指向的值,它将无法正常工作.例如

To: Espen Harlinn

This looks neat I will give it a try. However why does not my solution work? Actually I have noticed if I just try to change the value where a pointer is pointing to in a function it does not work. e.g.,

void insertAtStart(node* head, int data)
{
    head=NULL;
}



现在,如果我打电话到某个地方:



Now if I call somewhere:

node* head = someOtherPointer;
insertAtStart(head, data);
// after calling this function head still points where it was pointing, instead of pointing now to NULL?? Why? just interesting.


这篇关于关于链表,C ++的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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