Prints The Integers In The Opposite Order

Code Id 10
Date Updated 3/7/2010
Title Prints the integers in the opposite order  
Description
Write a program that reads a list of integers and prints the integers in the opposite order, one per line.
Do not ask the user in advance how many integers there are.
For example, if the input is 3 1 4 1 5,
the output will be 5 1 4 1 3 on five lines.
You may assume that each integer is between -10000 and 10000. You must use memory proportional to the number of integers.
If not enough memory is available, print a message on stderr and exit. 
                                  
Codes Snippet
#include 
#include 

int main(void)
{
  int *x = 0;
  int xspace = 0;
  int xlen = 0;
  int d;

  while (scanf("%d",&d) == 1) {
    if (xlen == xspace) {
      xspace = xspace * 2 + 1;
      x = realloc(x,xspace * sizeof(int));
      if (!x) {
        fprintf(stderr,"out of memoryn");
        exit(111);
      }
    }
    x[xlen++] = d;
  }

  while (xlen > 0)
    printf("%dn",x[--xlen]);

  exit(0);
}

Comments are closed.