[ create a new paste ] login | about

Link: http://codepad.org/RNB6vMYe    [ raw code | fork ]

C, pasted on Jan 17:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Lib_node {
  void *data;
  struct Lib_node *left, *right;
};

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;
}

#define BUFFSIZE 3 /* >= 2 */
char *getline(void)
{
  static char inbuff[BUFFSIZE];
  char *outbuff_malloc, *tmpbuff;
  char *p;
  int fEOL;

  if ((outbuff_malloc = malloc(1)) == NULL)
    return NULL;
  *outbuff_malloc = '\0';
  fEOL = 0;
  do {
    if (fgets(inbuff, BUFFSIZE, stdin) == NULL) {
      free(outbuff_malloc);
      outbuff_malloc = 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);
  return outbuff_malloc;
}

int cmp(char *a, char *b)
{
  char *p, *q, c;
  double x, y;
  for (p = a, q = b; ; p++, q++) {
    if (*p == '\0' && *q != '\0')
      return -1;
    if (*q == '\0' && *p != '\0')
      return 1;
    if (*p == *q) {
      if (*p == '\0')
        return 1;
      else
        continue;
    }
    x = (double)*p;
    y = (double)*q;
    if (*p >= 'a' && *p < 'z') {
      x = x - 'a' + 'A';
      x = x + 0.5;
    }
    if (*q >= 'a' && *q < 'z') {
      y = y - 'a' + 'A';
      y = y + 0.5;
    }
    return (x < y) ? -1 : 1;
  }
}

int main()
{
  struct Lib_node *root;
  char *inputLine_malloc, *p;

  root = NULL;
  while ((inputLine_malloc = getline()) != NULL) {
    lib_add_list(&root, inputLine_malloc, (int (*)(void *, void *))cmp);
  }
  while ((p = (char *)lib_delmin_list(&root)) != NULL) {
    printf(">>%s\n", p);
    free(p);
  }
  return 0;
}
/* end */


Output:
No errors or program output.


Create a new paste based on this one


Comments: