/* Program to use a dynamically allocated linked list to implement a queue */ #include #include #include #define NAMESIZE 255 #define DEBUG 0 typedef struct node { char name[NAMESIZE]; struct node *next; } NODE; /* print_list prints the entire list out to stdout */ void print_list(NODE *head) { NODE *current; if (DEBUG) printf("In print_list...\n"); current = head; printf("Complete list:\n"); while (current->next != NULL) { printf("%s\n", current->name); current = current->next; } printf("%s\n", current->name); printf("\n\n"); } /* enqueue adds a node to the end of the list */ NODE *enqueue(NODE *head, char *addData) { NODE *tail, *new; if (DEBUG) printf("In enqueue, addData = %s...\n", addData); if (head == NULL) { head = (NODE *)malloc(sizeof(NODE)); head->next = NULL; strncpy(head->name, addData, NAMESIZE); } else { tail = head; while (tail->next != NULL) tail = tail->next; new = (NODE *)malloc(sizeof(NODE)); tail->next = new; strncpy(new->name, addData, NAMESIZE); new->next = NULL; } return(head); } /* dequeue removes a node from the front of the list and prints it */ NODE *dequeue(NODE *head) { NODE *newHead; if (DEBUG) printf("In dequeue, head->name is %s...\n", head->name); newHead = head->next; printf("dequeue: %s\n", head->name); free(head); return(newHead); } /* main (duh) */ int main() { NODE *head; FILE *infile; char command[NAMESIZE], name[NAMESIZE]; if (DEBUG) printf("In main, opening file...\n"); infile = fopen("queue_input.list", "r"); if (infile == NULL){ printf("Error opening input file \"queue_input.list\"\n"); return(0); } /* set up an initial list */ head = NULL; /* main loop */ fscanf(infile, "%s %s", command, name); while (!feof(infile)) { if (DEBUG) printf("Main loop, read %s %s...\n", command, name); if (strcmp(command, "enqueue") == 0) { head = enqueue(head, name); } else if (strcmp(command, "dequeue") == 0) { head = dequeue(head); } fscanf(infile, "%s %s", command, name); } fclose(infile); print_list(head); }