递归统计链表中与线性链表最后一个节点数据相同的节点数量

问题描述 投票:0回答:3

我正在练习 LLL 递归,目前我陷入了这个问题。这是我到目前为止所拥有的:

count_last(node* head, int &last_node_data)
{
     if(!head) return 0;
     if(!head->next)
     {last = head->data;
       return 0;
     }
      count_last(head->next,last);
      if(head->data == last)
           //Increase count by 1;
  }

如何增加计数?当我用递归向后工作时(从列表的末尾开始),我真的很挣扎。谢谢!

c++ recursion
3个回答
0
投票

你可以:

  • 使用静态局部变量(仅一次性使用,因为它永远不会重新初始化)
  • 使用全局变量
  • 将计数作为参数传递,返回更新后的计数。
  • 将指向计数的指针作为参数传递,并更新它

0
投票

尝试这样的事情:

int count_last(node* head, int &last_node_data)
{
    if (!head) return 0;

    // if you don't want to include the last
    // node in the count, you can filter it out...
    //
    // if (!head->next) return 0;

    return ((head->data == last_node_data) ? 1 : 0) + count_last(head->next, last_node_data);
}

0
投票
int count_last(node* head, int& last_node_data)
{
    if(!head) return 0;
    if(!head->next) {
        last_node_data = head->data;
        return 0;
    }
    int count += count_last(head->next, last_node_data);
     
    if(head->data == last_node_data)
        ++count;
}
© www.soinside.com 2019 - 2024. All rights reserved.