/* Sample solutions for the first three problems in the homework. When you answer other problems, keep the portion above the line // DO NOT MAKE CHANGES ABOVE THIS LINE. After you implement the function defined in each problem, complete the main() function to create a linked list to test your function. If you find the function(s) defined for problem 1 and/or problem 2 useful, feel free to use them. Gang Qu */ #include #include #define NEW(x) (x*)malloc(sizeof(x)) typedef struct node { int * data; struct node * next; } NODE; typedef struct { NODE *head; } ROOT; NODE * make_node (int *data) { NODE * temp; temp = NEW(NODE); if (temp != NULL) { temp->data = data; temp->next = NULL; } return temp; } ROOT * make_root (void) { ROOT * temp; temp = NEW(ROOT); if (temp != NULL) temp->head = NULL; return temp; } void compete(ROOT *, ROOT *); // documentation.... // DO NOT MAKE CHANGES ABOVE THIS LINE. int insert_at_tail(ROOT *r, int *d) // problem 1. { NODE *temp, *curr ; temp = make_node(d); if (temp == NULL) return -1; // fail, cannot create new NODE if (r == NULL) { r = make_root(); if (r == NULL) return -1; // fail, cannot create ROOT } curr = r->head; // when the linked list is empty if (curr == NULL) { r->head = temp; return 0; } for (; curr->next != NULL; curr = curr->next); // find the tail, empty loop body curr->next = temp; // link node temp to the linked list // at the tail. return 0; } void display_list(ROOT *r) // problem 2. { NODE *temp; if (r == NULL) return; // undefinted linked list if (r->head == NULL) return; // empty linked list for (temp = r->head; temp != NULL; temp = temp->next) printf("%d->", *temp->data); printf("/\n"); } int main(void) { int value, i; int *p; NODE *temp; ROOT *r, *s; r = make_root(); if (r == NULL) return -1; s = make_root(); if (s == NULL) return -1; for (i=0; i<10; i++) { value = rand()%11 + 10; p = NEW(int); if (p == NULL) return -1; *p = value; insert_at_tail(r, p); // insert at tail // display_list(r); // question 2 value = rand()%11 + 10; p = NEW(int); if (p == NULL) return -1; *p = value; insert_at_tail(s, p); } display_list(r); display_list(s); compete(r, s); return 0; } void compete(ROOT *r, ROOT *s) { NODE *temp_r, *temp_s; int a, b; int wins = 0, losses = 0, ties = 0; int rounds = 1; if (r == NULL) return; // undefinted linked list if (s == NULL) return; // undefinted linked list if (r->head == NULL) return; // empty linked list if (s->head == NULL) return; // empty linked list for (temp_r = r->head, temp_s = s->head; temp_r != NULL && temp_s != NULL; temp_r = temp_r->next, temp_s = temp_s->next) { a = *temp_r->data; b = *temp_s->data; if (a > b) {wins++;} if (a < b) {losses++;} if (a == b) {ties++;} printf("Round %d: First list has %d wins, %d losses, %d ties\n", rounds, wins, losses, ties); rounds++; } return; }