简体   繁体   English

将 LinkedList 值传递给函数 - C

[英]Passing a LinkedList value to a function - C

I have a file having four columns of 10 test data and these data will be stored in four variables to a linkedlist .我有一个包含四列 10 个测试数据的文件,这些数据将存储在四个变量中到一个linkedlist

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

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

My objective is to have a one function to calculate sum and average of those 10 data so that i don't have to have four separate calcsum functions.我的目标是有一个函数来计算这 10 个数据的总和和平均值,这样我就不calcsum四个单独的calcsum函数。

How to pass these values separately to a calcSum function?如何将这些值分别传递给calcSum函数?

For example if i need to find the sum of proxy how to pass this to the function?例如,如果我需要找到代理的总和如何将其传递给函数?

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

If I understand you correctly then this is what you are looking for:如果我理解正确,那么这就是你要找的:

You can just create an enum , which defines the desired member and pass it to the function.您可以创建一个enum ,它定义所需的成员并将其传递给函数。 The function then gets the appropriate member accordingly to the value of the 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM