将LinkedList值传递给函数 - C.

时间:2016-04-26 16:10:01

标签: c linked-list

我有一个包含4列10个测试数据的文件,这些数据将存储在4个变量中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;
        }
}

1 个答案:

答案 0 :(得分:1)

如果我理解正确,那么这就是你要找的东西:

您可以创建一个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;
}