【问题标题】:a function that count the odd elements in list with startup pointer START使用启动指针 START 计算列表中奇数元素的函数
【发布时间】:2019-04-27 12:56:44
【问题描述】:

我需要用启动指针开始计算列表中的奇数

struct elem {
    int key; 
    elem *next;

}
 *start = NULL;

// List Function 

void list() {
    if (start)
    {
        cout << "\nList";
        elem *p = start;
        while (p)
        {
            cout << p->key << "\t";
            p = p->next;
        }
    }
    else
    {
        cout << "\nEmpty list";
    }
}

// 添加

void add(int n) {
    if (start==NULL || start ->key > n)
    {
        add_b(n);
    }
    else
    {
        elem *p = start;
        while (p->key <= n && p->next)
        {
            p = p->next;
    }
    add_e(n);

    }
}

// 驱动函数

int main() {

    int d;

    do
    {
        cin >> d;
        if (d)
        {
            add(d), list();
        }
    } while (d);

    system("pause");
    return 0;
}

我不知道我需要从哪里开始我的 for 循环来计算奇数。

请有人给我演示或类似的东西,因为我真的不明白该怎么做,它真的很有帮助

【问题讨论】:

  • 你认为add(d), list();实际上应该做什么?你可能想回到你的教科书。
  • 听起来像你想要的std::count_if
  • @πάνταῥεῖ 向我展示列表函数的文本,如 list1 list2 等。
  • @JesperJuhl 当我运行程序时,我开始输入数字,点击 0 按钮后,我想显示我已经输入的奇数的计数
  • 如何在list() 末尾使用cout &lt;&lt; endl; 刷新输出?

标签: c++ list pointers count


【解决方案1】:

如果我理解正确,您需要为列表编写一个递归函数来计算列表中的奇数。

递归函数可以如下所示

unsigned int count_odds( struct elem *start )
{
    return start == NULL ? 0 : ( start->key & 1 ) + count_odds( start->next );
}

并且被称为

unsigned int n = count_odds( start );

除了函数返回类型unsigned int,您还可以使用更好的类型size_t

【讨论】:

  • 我尝试使用你的函数,这就是我想要的,但什么也没发生我的意思是当我输入 0 来完成程序时,程序不会显示奇数元素数
  • @stamatow 你是否包含了一个语句,例如这个 printf("The number of odd numbers is %u\n", n); ?
  • @stamatow 您将函数定义包含在错误的位置(它似乎在另一个函数中)。检查您的代码。
  • 我得到了一些答案并说 2 但真正的答案需要在那个情况 7 中?也许在 if 语句中?
  • @bruno 你的意思是我需要停止编程?
【解决方案2】:

奇数计数伪代码

int count_odd(list)
{
    int count = 0;
    for (current_node = start_of_list until end_of_list)
    {
        if (current_node->value is odd)
            ++count;
    }

    return count;
}

【讨论】:

  • 我复制并粘贴此内容,但没有任何反应
  • @stamatow 这不是复制粘贴的答案,而是pseudocode。它显示了原理,算法。您必须编写自己的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-09
  • 1970-01-01
  • 2011-05-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多