Simple Linked List

/*
| header file for points / linked-list examples
|   2020-10-02
*/
#ifndef _LINK_
#define _LINK_

struct Point {
    double x, y, z, weight;
    struct Point *next;
} ;

double length(struct Point *p);
void addtolist(struct Point **headp, struct Point *cursor);

#endif

addtolist()

// addtolist() function for linked-list example program
//  2020-10-01
#include <stddef.h> // for NULL definition

// struct declaration are typically kept in a .h header file
// along with prototypes, but repeated here for simplicity:
struct Point {
    double x, y, z, weight;
    struct Point *next;
} ;

void addtolist(struct Point **headp, struct Point *cursor)
{
    struct Point **p = headp;
    while (*p != NULL) {
        p = &(*p)->next;
    }
    *p = cursor;
}
 /*
    if (*headp == NULL)
            *headp = cursor;
    else {
        (*headp)->next = cursor;
    }
*/

main() and length()

/* point-example2.c
|       Building a LINKED LIST !
| 2020-10-01
*/
#include <stdio.h>
#include <stdlib.h>     // malloc()
#include <math.h>       // sqrt()

struct Point {
    double x, y, z, weight;
    struct Point *next;
} ;

double length(struct Point *p);
void addtolist(struct Point **headp, struct Point *cursor);

int main(int argc, char **argv)
{
    struct Point *mypoints = NULL;
    struct Point *cursor;
    double x, y, z, w;

    //for (p = &(mypoints[0]); p < &(mypoints[10]); p++) {
    printf("Enter (x, y, z), weight? ");
    while ( 4 == scanf(" %lf %lf %lf %lf", &x, &y, &z, &w) ) {
        cursor = (struct Point *)malloc( sizeof(struct Point) );
        cursor->x = x;
        cursor->y = y;
        cursor->z = z;
        cursor->weight = w;
        cursor->next = NULL;

        addtolist(&mypoints, cursor);
    }

    printf("\n");
    for (cursor = mypoints; cursor != NULL ; cursor = cursor->next) {
        printf("%p:   (%.2lf, %.2lf, %.2lf), %lf, %lf\n",
            cursor, cursor->x, cursor->y, cursor->z,
            cursor->weight, length(cursor)
        );
    }

    return 0;
}

double length(struct Point *p)
{
    return sqrt( p->x * p->x  +  p->y * p->y  + p->z * p->z );
}


example testdata file


1  1  1  10
2  2  2  25
546 35 5466  32131
3.2  5.4  7.8  478
-4.1 -4.5 6.5 1456

1  1  1  10
2  2  2  25
546 35 5466  32131
3.2  5.4  7.8  478
-4.1 -4.5 6.5 1456

1  1  1  10
2  2  2  25
546 35 5466  32131
3.2  5.4  7.8  478
-4.1 -4.5 6.5 1456

1  1  1  10
2  2  2  25
546 35 5466  32131
3.2  5.4  7.8  478
-4.1 -4.5 6.5 1456

1  1  1  10
2  2  2  25
546 35 5466  32131
3.2  5.4  7.8  478
-4.1 -4.5 6.5 1456

1  1  1  10
2  2  2  25
546 35 5466  32131
3.2  5.4  7.8  478
-4.1 -4.5 6.5 1456


linked list picture