#include #include // c version of linked list, featuring malloc. See also node.cc for elegant C++ node definition typedef struct node_s // real C { char * name; int value; //price of fruit struct node_s *next; // we'd like node*, but not defined yet } node; // now we can declare or create nodes: node* build(const char* filename) // build linked list from a file // return pointer to first node { // each line of form "apple 66" node* head=0; // initially empty list node* tail; // hold pointer to last node in list node* anode; char * afruit; int aprice; FILE * f = fopen(filename,"r"); // NOTE syntax for EOF test while(EOF != fscanf(f,"%ms%d", &afruit, &aprice)) { // implicit malloc for string // printf ("%s\n", afruit); anode = malloc(sizeof(node)); // allocate space for node anode -> name = afruit; // fill it in, point to str. anode -> value = aprice; anode -> next = 0; // currently no next if (! head) head=tail=anode; // it is first and last elem. else { tail -> next = anode; // linked at tail tail = anode; // it is new tail } } fclose(f); return head; // list all set up } void list(node* head) { while (head) { printf (" %-12s %4d\n", head->name, head->value); // -12 for left-justify head = head -> next; } } node* delete(char* victim, node* head) { // delete (one) node matching victim, return possibly new head node* curr = head; node* prev; node* newhead; while (curr) { if ( strcmp (curr -> name, victim) == 0) // found the victim if (curr==head) { // should deallocate newhead = head -> next; //first, save pointer to new head free( curr -> name); // release string space free (curr); // release node space return newhead; } else { prev -> next = curr -> next; // link around curr free( curr -> name); // release string space free (curr); // release node space return head; // unchanged } prev = curr; // may need to link around a deletion curr = curr -> next; // keep looking } return head; // unchanged } int main(){ node* head = build("linklist.txt"); list(head); //see the list head = delete ("grape", head); puts("After delete----"); list(head); //see the list return 0; }