#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
/* #define DEBUG */
#if defined(DEBUG)
#include "xmalloc.h"
#else
#define xmalloc(x, y) malloc(x)
#define xfree(x, y) free(x)
#define xrealloc(x, y, z) realloc(x, y)
#define xmallocdump()
#endif
#define ID_GETLINE 1001
#define ID_NODE 1002
#define BUFFSIZE 3 /* >= 2 */
char *mygetline(FILE *fp) {
static char inbuff[BUFFSIZE];
char *outbuff_malloc, *tmpbuff;
char *p, *r;
int fEOL;
if ((outbuff_malloc = xmalloc(1, ID_GETLINE)) == NULL) {
return NULL;
}
*outbuff_malloc = '\0';
fEOL = 0;
do {
r = fgets(inbuff, BUFFSIZE, fp);
if (r == NULL)
break;
for (p = inbuff; *p != '\0'; p++)
;
if (*(p - 1) == '\n')
fEOL = 1;
if ((tmpbuff = xrealloc(outbuff_malloc, strlen(outbuff_malloc) + strlen(inbuff) + 1, ID_GETLINE)) == NULL) {
xfree(outbuff_malloc, ID_GETLINE);
return NULL;
}
strcat(tmpbuff, inbuff);
outbuff_malloc = tmpbuff;
} while (!fEOL);
if (strlen(outbuff_malloc) > 0) {
for (p = outbuff_malloc; *p != '\0'; p++)
;
if (*(p - 1) == '\n')
*(p - 1) = '\0';
return outbuff_malloc;
}
xfree(outbuff_malloc, ID_GETLINE);
return NULL;
}
struct student {
int no;
char *name;
int point;
struct student *next;
};
void list_add(struct student **root, int n, char *name, int point) {
struct student *p;
if (*root) {
list_add(&((*root)->next), n, name, point);
} else {
if ((p = xmalloc(sizeof(struct student), ID_NODE))) {
p->no = n;
p->name = name;
p->point = point;
p->next = 0;
*root = p;
}
}
}
void task_inputData(struct student **root, int n) {
char *name, *p;
int point;
printf("name: ");
if ((name = mygetline(stdin))) {
printf("point: ");
if ((p = mygetline(stdin))) {
point = atoi(p);
xfree(p, ID_GETLINE);
list_add(root, n, name, point);
}
}
}
void task_dumpData(struct student *p) {
if (!p)
return;
printf("%4d %15s %5d\n", p->no, p->name, p->point);
task_dumpData(p->next);
}
struct student *task_findMaxData(struct student *p) {
struct student *q;
if (!p->next) {
return p;
}
q = task_findMaxData(p->next);
if (p->point > q->point)
return p;
else
return q;
}
void task_release(struct student **root) {
if (*root) {
xfree((*root)->name, ID_GETLINE);
task_release(&(*root)->next);
xfree(*root, ID_NODE);
*root = 0;
}
}
int main() {
char *p;
int i, n;
struct student *root, *stu;
root = NULL;
printf("n = ");
p = mygetline(stdin);
if (p) {
n = atoi(p);
for (i = 0; i < n; i++)
task_inputData(&root, i + 1);
task_dumpData(root);
stu = task_findMaxData(root);
printf("maximum: %s (%d points)\n", stu->name, stu->point);
task_release(&root);
xfree(p, ID_GETLINE);
}
xmallocdump();
return 0;
}
/* end */