#include #include #include #include #include #include #include #include typedef struct linked_list { int data; struct linked_list *next; } LL; typedef struct linked_list Q; void init_list(LL **head); int count_list(LL **head); int add_list(LL **head, int data); void print_list(LL **head); int process_data(Q **q); int add_queue(Q **q, int data); void init_queue(Q **q); int count_queue(Q **q); void init_list(LL **head) { assert(head != NULL); *head = NULL; } int count_list(LL **head) { assert(head != NULL); if (*head == NULL) { return 0; } else { int i = 1; LL *ptr; ptr = *head; while (ptr->next != NULL) { ptr = ptr->next; i++; } return i; } } int add_list(LL **head, int data) { LL *ptr, *newptr; assert(head != NULL); ptr = *head; newptr = malloc(sizeof(LL)); if (newptr == NULL) { perror("malloc"); return 0; } newptr->data = data; newptr->next = NULL; if (*head == NULL) { *head = newptr; } else { while (ptr->next != NULL) ptr = ptr->next; ptr->next = newptr; } return 1; } void print_list(LL **head) { LL *ptr; assert(head != NULL); ptr = *head; while (ptr != NULL) { printf("%d\n",ptr->data); ptr = ptr->next; } } int process_data(Q **q) { Q *ptr; assert(q != NULL); ptr = *q; if (ptr == NULL) return 0; *q = ptr->next; printf("processing %d\n",ptr->data); free(ptr); } int add_queue(Q **q,int data) { assert(q != NULL); return add_list(q,data); } void init_queue(Q **q) { assert(q != NULL); init_list(q); } int count_queue(Q **q) { assert(q != NULL); return count_list(q); } main(int argc, char *argv[]) { Q *q; FILE *fp; char line[200]; if (argc != 2) { fprintf(stderr,"usage: %s file\n",basename(argv[0])); exit(1); } fp = fopen(argv[1], "r"); if (fp == NULL) { perror("fopen"); exit(1); } init_queue(&q); fgets(line, sizeof(line), fp); while (!(feof(fp))) { int data; // receive request if (line[0] == '?') { // how many requests in queue int num = count_queue(&q); printf("queue is %d long\n",num); print_list(&q); // element in queue } else if (line[0] == 'a') { // new request if (1 == sscanf(&line[1],"%d",&data)) add_queue(&q, data); printf("adding %d\n",data); } else if (line[0] == 'd') { // new request process_data(&q); } fgets(line, sizeof(line), fp); } fclose(fp); exit(0); }