【问题标题】:I have created function to modify a node in Linkedlist in C++ but its not working: [closed]我已经创建了在 C++ 中修改链接列表中的节点的函数,但它不起作用:[关闭]
【发布时间】:2021-01-22 21:00:41
【问题描述】:

此函数在 LinkedList 中创建,用于修改给定位置的节点。但是,这个函数不能正常工作,它给出了一些随机值。

  void update_data(int old, int new_data) {//Function toupdate node
                Node *curr=header;//Data members
               int pos = 0;
               while(curr->next!=NULL) {
                  if(curr->isbn == old)
                  {
                     curr->isbn = new_data;
                     cout<<old<<" Found at position "<<pos<<" Replaced with "<<new_data<<endl;;
                  }
                  curr = curr->next;
                  pos++;
               }
               }

【问题讨论】:

  • 是时候开始调试了!祝你好运!
  • @M. Ameen Akbar 没有使用变量 pos。
  • @M. Ameen Akbar 你说这个功能不能正常工作是什么意思?
  • 如果列表为空且currNULL,请考虑while(curr-&gt;next!=NULL) 处发生的情况。
  • 与您的Rubber Duck 坐下来讨论是否值得在找到并更新项目后继续搜索列表。

标签: c++ oop linked-list singly-linked-list function-definition


【解决方案1】:

对于初学者来说,变量pos 没有在函数中使用。

其次是while循环的条件

while(curr->next!=NULL) {

不正确,通常会调用未定义的行为,因为指针 header 可以等于 nullptr。此外,如果列表只包含一个由指针头指向的节点,并且其数据成员isbn等于变量old的值,则它不会被更改。

该函数不应输出任何消息。

函数可以如下所示

void update_data( int old, int new_data ) 
{//Function toupdate node
    for ( Node *curr = header; curr != nullptr; curr = curr->next ) 
    {
        if ( curr->isbn == old )
        {
            curr->isbn = new_data;
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-18
    • 2015-05-05
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    相关资源
    最近更新 更多