c - 将 LinkedList 值传递给函数 - C

标签 c linked-list

我有一个包含四列 10 个测试数据的文件,这些数据将以四个变量的形式存储到一个 linkedlist 中。

struct node
{
        float proxy;
        float planAdded;
        float actualAdded;
        float devHours;

        struct node *next;
}*head = NULL, *current = NULL;

我的目标是用一个函数来计算这 10 个数据的总和和平均值,这样我就不必有四个单独的 calcsum 函数。

如何将这些值分别传递给 calcSum 函数?

例如,如果我需要找到代理的总和,如何将其传递给函数?

float calcSumX(nodeT *head, head->value)
{
        current = head;
        float sum = 0;
        while(current != NULL)
        {
                sum += current->x;
                current = current->next;
        }
}

最佳答案

如果我理解正确,那么这就是您要查找的内容:

您可以只创建一个 enum,它定义了所需的成员并将其传递给函数。该函数然后根据 enum 的值获取适当的成员。

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
  float proxy;
  float planAdded;
  float actualAdded;
  float devHours;

  struct node *next;
} node; 

node *head = NULL, *current = NULL;

typedef enum {proxy, planAdded} member_op;

float getMemberValue(member_op op)
{
  if (op == proxy)
    return current->proxy;
  else if (op == planAdded)
    return current->planAdded;
  else return 0;
}

float calcSumX(node *head, member_op op)
{
  current = head;
  float sum = 0;
  while (current != NULL)
  {
    sum += getMemberValue(op);
    current = current->next;
  }
  printf("sum: %f\n", sum);
  return sum;
}

int main(void)
{
  node *first = (node*)malloc(sizeof(node));
  node *second = (node*)malloc(sizeof(node));
  node *third = (node*)malloc(sizeof(node));

  first->proxy = 1;
  second->proxy = 2;
  third->proxy = 3;

  first->planAdded = 4;
  second->planAdded = 5;
  third->planAdded = 6;

  first->next = second;
  second->next = third;
  third->next = NULL;

  head = first;
  calcSumX(head, proxy);
  calcSumX(head, planAdded);

  free(first);
  free(second);
  free(third);
  return 0;
}

关于c - 将 LinkedList 值传递给函数 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36870305/

相关文章:

c - 使用 GCC 将 warn_unused_result 应用于所有函数

c++ - 插入节点时对链表进行排序

c - For 循环不以空终止符终止

c - 是否有机器,其中 sizeof(char) != 1,或至少 CHAR_BIT > 8?

c - 为什么这个 C 链表会损坏?

Python : why doesn't a. pop() 修改链表(自定义链表类)

c - 链表不能在 C 中正确打印/添加

java链表复制构造函数和字符串构造函数

c - 如何为C程序制作插件界面

c - Windows 上的 clang 中缺少 M_PI_2