C 链接列表和总和问题

C++ Linked list and sum issue

本文关键字:问题 列表 链接      更新时间:2023-10-16

我在下面的代码上不断遇到错误,我不知道为什么。

int sum(struct node *head)
{
    int total = 0;
    struct node *temp = head;
    while (temp != NULL)
    {
        total += temp->data;
        temp = temp->next;
    }
}

错误c4716'sum':必须返回值

就像错误消息所说的那样,您需要return statment:

int sum(struct node *head)
{
    int total = 0;
    struct node *temp = head;
    while (temp != NULL)
    {
        //cout << temp->data << 'n';    //debug
        total += temp->data;
        temp = temp->next;
    }
    return total; // <-- add this!
}

在编写int sum(struct node *head)时,这意味着您的功能应返回整数值。因此,您可以做的是您可以在功能结束时添加返回语句。

类似的东西

    int sum(struct node *head)
    {
    int total = 0;
    struct node *temp = head;
    while (temp != NULL)
    {
        total += temp->data;
        temp = temp->next;
    }
    return total;
    }

和您称之为此函数的语句只需将该函数分配给任何整数变量。

int t = sum(head);

希望对

有帮助