如何使用链表在一个节点中存储两个实数

How to use a linked List to store two real numbers in one node

我创建了 20 个节点来存储 20 个元素,但我只需要 10 个节点来将这 20 个元素存储为一个节点中的两个元素。 这是我的代码

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

struct list_el
{
  float            val;
  struct list_el * next;
};

typedef struct list_el item;

int main()
{
  item *curr, *head;
  head = NULL;

  FILE * pointer = NULL;

  float  array[20];
  int    j;
  double xsq, ysq, B1, B0, R, rsq, rpart, rdevide, estimate;
  double estimate;
  double total_x   = 0;
  double total_y   = 0;
  double total_xsq = 0;
  double total_ysq = 0;
  double total_xy  = 4303108.0;
  double avg_x     = 0;
  double avg_y     = 0;

  pointer = fopen("dummy.txt", "r");

  //Store the data to a array from the pointer
  for(j = 0; j < 20; j++)
  {
    fscanf(pointer, "%f", &array[j]);
  }

  //make nodes and store data inside the each node head.. in this code segment i want to store two elements in one node
  for(j = 0; j < 20; j++)
  {
    curr       = (item *)malloc(sizeof(item));
    curr->val  = array[j];
    curr->next = head;
    head       = curr;
  }

  curr = head;

  for(j = 0; j < 20; j++)
  {
    if(j < 10)
    {
      printf("%.2f\n", curr->val);
      total_y   = total_y + curr->val;
      ysq       = curr->val;
      total_ysq = total_ysq + (ysq * ysq);
      curr      = curr->next;
    }
    else
    {
      printf("%.2f\n", curr->val);
      total_x   = total_x + curr->val;
      xsq       = curr->val;
      total_xsq = total_xsq + (xsq * xsq);
      curr      = curr->next;
    }
  }

  //calculate the average of data
  avg_x = total_x / 10.0;
  avg_y = total_y / 10.0;

  printf("Average \n");
  printf("X: %.3f\n", avg_x);
  printf("Y : %.3f\n\n", avg_y);

  fclose(pointer);
  return 0;

} //End of Main

dummy.txt:

130 650 99 150 128 302 95 945 368 961 186 699 132 272 291 331 199 1890 788 1601

只需在结构上添加一个浮点数 list_el

struct list_el
{
  float val1;
  float val2;
  struct list_el * next;
};

I have created 20 nodes to store 20 elements but i just need 10 nodes to store those 20 elements as two element in one node.

有两种方法可以实现。

第一种方式

struct list_el
{
    float val1;
    float val2;
    struct list_el * next;
};

另一种方式

#define NUM_VALS 2

struct list_el
{
    float val[NUM_VALS];
    struct list_el * next;
};