| structures/lists.c - Hele programmet. | Lektion 12 - slide 26 : 36 Program 4 |
#include <stdio.h>
#include <stdlib.h>
struct point {int x; int y;};
typedef struct point point;
void prnt_point(point p){
printf("Point: %i, %i\n", p.x, p.y);
}
struct cons_cell {
void *data;
struct cons_cell *next;
};
typedef struct cons_cell cons_cell;
/* Returns a pointer to a new cons cell,
which refers data and next via pointers*/
cons_cell *cons(void *data, cons_cell *next){
cons_cell *result;
result = (cons_cell *)malloc(sizeof(cons_cell));
if (result == NULL){
printf("Out of memory. Bye.");
exit(EXIT_FAILURE);
}
result->data = data;
result->next = next;
return result;
}
/* Return the head reference of the cons cell */
void *head(cons_cell *cell){
return cell->data;
}
/* Return the tail refererence f the cons cell */
cons_cell *tail(cons_cell *cell){
return cell->next;
}
/* Change the data position of cell to new_head */
void set_head(cons_cell *cell, void *new_head){
cell->data = new_head;
}
/* Change the next position of cell to new_tail */
void set_tail(cons_cell *cell, cons_cell *new_tail){
cell->next = new_tail;
}
int main(void) {
cons_cell *points;
point p1 = {1,2}, p2 = {3,4}, p3 = {5,6};
points = cons(&p1,
cons(&p2,
cons(&p3,
NULL)));
while (points != NULL) {
prnt_point(*((point*)(head(points))));
points = tail(points);
}
return 0;
}