#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 {
int num;
};
static int flagS;
int cmp(struct data *a, struct data *b)
{
if (flagS == 1)
return (b->num > a->num) ? 1 : -1;
else
return (a->num > b->num) ? 1 : -1;
}
#define BUFFSIZE 3 /* >= 2 */
char *getline(FILE *fp)
{
static char inbuff[BUFFSIZE];
char *outbuff_malloc, *tmpbuff;
char *p, *q;
int fEOL;
if ((outbuff_malloc = malloc(1)) == NULL) {
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);
return NULL;
}
strcat(tmpbuff, inbuff);
outbuff_malloc = tmpbuff;
} while (!fEOL);
if (q == NULL) {
free(outbuff_malloc);
return NULL;
}
return outbuff_malloc;
}
void reg(struct Lib_node **root, int n)
{
struct data *d;
if ((d = malloc(sizeof(struct data))) == NULL) {
fprintf(stderr, "cannot allocate enough memory.\n");
exit(-1);
}
d->num = n;
if (lib_add_list(root, d, (int (*)(void *, void *))cmp) == NULL) {
fprintf(stderr, "cannot allocate enough memory.\n");
exit(-1);
}
}
void output(struct Lib_node **root, FILE *fp)
{
struct data *p;
while ((p = lib_delmin_list(root)) != NULL) {
fprintf(fp, "%d\n", p->num);
free(p);
}
}
#define INPUTFILE "in.txt"
#define OUTPUTFILE "out.txt"
int main()
{
FILE *fp;
char *inputLine_malloc;
struct Lib_node *root;
int n;
printf("並び替え方法を指定してください.(1:昇順, 2:降順)\n");
scanf("%d", &n);
if (n == 1)
flagS = 1;
else
flagS = 0;
if ((fp = fopen(INPUTFILE, "rt")) == NULL) {
fprintf(stderr, "cannot open the input file, aborted.\n");
exit(-1);
}
lib_init_list(&root);
while ((inputLine_malloc = getline(fp)) != NULL) {
if (sscanf(inputLine_malloc, "%d", &n) == 1)
reg(&root, n);
free(inputLine_malloc);
}
fclose(fp);
if ((fp = fopen(OUTPUTFILE, "wt")) != NULL) {
output(&root, fp);
printf("並び替えた結果をファイルへ出力しました.\n");
fclose(fp);
}
return 0;
}
/* end */