[ create a new paste ] login | about

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

C, pasted on Dec 9:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

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

struct node {
  int num;
  struct node *next;
};

void push_list(struct node **root, int num)
{
  struct node *p;

  if (*root == NULL) {
    if ((p = malloc(sizeof(struct node))) == NULL) {
      fprintf(stderr, "memory full.\n");
      exit(-1);
    }
    p->num = num;
    p->next = NULL;
    *root = p;
  } else
    push_list(&((*root)->next), num);
}

int pop_list(struct node **root)
{
  int num;
  struct node *p;

  if (*root != NULL) {
    num = (*root)->num;
    p = *root;
    *root = (*root)->next;
    free(p);
  }
  return num;
}

int main()
{
  char *p;
  struct node *root;
  int i, num;

  root = NULL;
  while ((p = getline(stdin)) != NULL) {
    push_list(&root, atoi(p));
    free(p);
  }
  printf("------------\n");
  i = 1;
  if (root != NULL) {
    while (num = pop_list(&root), root != NULL)
      printf("[%d]:%d\n", i++, num);
    printf("[%d]:%d\n", i, num);
  }
  return 0;
}
/* end */


Output:
1
------------


Create a new paste based on this one


Comments: