#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Lib_node {
void *data;
struct Lib_node *left, *right;
};
void lib_init_list(struct Lib_node **root)
{
*root = NULL;
}
void *lib_add_list(struct Lib_node **root, void *data, int (*cmp)(void *, void *))
{
int c;
struct Lib_node *node;
if (*root == NULL) {
if((node = malloc(sizeof(struct Lib_node))) == NULL) {
fprintf(stderr, "cannot allocate enoutgh memory.\n");
exit(-1);
}
node->data = data;
node->left = node->right = NULL;
*root = node;
return data;
}
if ((c = (*cmp)(data, (*root)->data)) < 0) {
return lib_add_list(&((*root)->left), data, cmp);
} else if (c > 0) {
return lib_add_list(&((*root)->right), data, cmp);
} else {
return (*root)->data;
}
}
void *lib_delmin_list(struct Lib_node **root)
{
void *data;
struct Lib_node *p;
if (*root == NULL)
return NULL;
if ((*root)->left != NULL)
return lib_delmin_list(&((*root)->left));
data = (*root)->data;
p = *root;
*root = p->right;
free(p);
return data;
}
struct data {
char *str;
int num;
};
int cmp(struct data *a, struct data *b)
{
return (b->num > a->num) ? 1 : -1;
}
void regline(struct Lib_node **root, char *line, int *error)
{
char *p, *q;
struct data *d;
p = q = line;
while (*p != '\t')
p++;
*p = '\0';
if ((d = malloc(sizeof(struct data))) == NULL) {
*error = 1;
return;
}
if((d->str = malloc(strlen(q) + 1)) == NULL) {
free(d);
*error = 1;
return;
}
strcpy(d->str, q);
p++;
d->num = atoi(p);
if (lib_add_list(root, d, (int (*)(void *, void *))cmp) == NULL) {
free(d->str);
free(d);
*error = 1;
}
*error = 0;
}
void output(struct Lib_node **root)
{
struct data *p;
while((p = lib_delmin_list(root)) != NULL) {
printf("%s\t%d\n", p->str, p->num);
free(p->str);
free(p);
}
}
#define BUFFSIZE 1024 /* >= 2 */
char *getline(FILE *fp, int *error)
{
static char inbuff[BUFFSIZE];
char *outbuff_malloc, *tmpbuff;
char *p, *q;
int fEOL;
if ((outbuff_malloc = malloc(1)) == NULL) {
*error = 1;
return NULL;
}
*outbuff_malloc = '\0';
fEOL = 0;
do {
if ((q = fgets(inbuff, BUFFSIZE, fp)) == NULL)
break;
for (p = inbuff; *p != '\0'; p++)
;
if (*(p - 1) == '\n') {
*(p - 1) = '\0';
fEOL = 1;
}
if ((tmpbuff = realloc(outbuff_malloc, strlen(outbuff_malloc) + strlen(inbuff) + 1)) ==NULL) {
free(outbuff_malloc);
*error = 1;
return NULL;
}
strcat(tmpbuff, inbuff);
outbuff_malloc = tmpbuff;
} while (!fEOL);
if (q == NULL) {
*error = 0;
free(outbuff_malloc);
return NULL;
}
*error = 0;
return outbuff_malloc;
}
int main(int argc, char *argv[])
{
char *inputLine_malloc;
struct Lib_node *root;
int error;
lib_init_list(&root);
while ((inputLine_malloc = getline(stdin, &error)) != NULL) {
regline(&root, inputLine_malloc, &error);
if (error != 0) {
free(inputLine_malloc);
fprintf(stderr, "memory full, dump.\n");
break;
}
free(inputLine_malloc); /* NULL ok */
}
output(&root);
return 0;
}
/* end */