#include #include 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 = malloc(sizeof(cons_cell)); 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; } /* Insert new_element after the cons-cell ptr_list */ void insert_after(void *new_element, cons_cell *ptr_list){ cons_cell *new_cons_cell, *ptr_after; /* Make a new cons-cell around new_element */ new_cons_cell= cons(new_element,NULL); /* Remember pointer to cons-cell after ptr_list */ ptr_after = tail(ptr_list); /* Chain in the new_cons_cell */ set_tail(ptr_list, new_cons_cell); /* ... and connect to rest of list */ set_tail(new_cons_cell, ptr_after); } /* Delete the element after ptr_list. Assume as a precondition that there exists an element after ptr_list */ void delete_after(cons_cell *ptr_list){ cons_cell *ptr_after, *ptr_dispose; /* cons-cell to delete later */ ptr_dispose = tail(ptr_list); /* The element to follow ptr_list */ ptr_after = tail(ptr_dispose); /* Mutate the tail of ptr_list */ set_tail(ptr_list, ptr_after); /* Free storage - only one cons-cell */ free(ptr_dispose); } int main(void) { cons_cell *points, *pl; point p1 = {1,2}, p2 = {3,4}, p3 = {5,6}, p_new = {11,12}; points = cons(&p1, cons(&p2, cons(&p3, NULL))); insert_after(&p_new, tail(points)); pl = points; while (pl != NULL) { prnt_point(*((point*)(head(pl)))); pl = tail(pl); } printf("\n\n"); delete_after(points); pl = points; while (pl != NULL) { prnt_point(*((point*)(head(pl)))); pl = tail(pl); } return 0; }