An implementation of the data structure stack. The size of this stack is STACKSIZE, the type of each element in the stack is element. Change the typedef of this element and recompile, then you have a stack of another type.
  • push an element into the stack, if it is not full yet.
  • pop an element out of the stack, if it is not empty (or pops out a zero).
  • duplicate the top element of the stack, if it is not empty (or a zero is returned).
  • up the stack by one element in the cyclic style.
  • down the stack by one element in the cyclic style.
  • list the stack elements, from top to bottom, to the stdout.
  • swaptop swaps the topest two elements in the stack, if there are enough of them.

  • #include <stdio.h>
    #include "stack.h"
    
    static int sp=0;
    element val[STACKSIZE];
    
    void push(element x) {
        if (sp < STACKSIZE)
    	val[sp++] = x;
        else
    	fprintf(stderr, "ERROR. push: stack full, can't push %g\n", x);
    }
    
    element pop(void) {
        if (sp > 0)
    	return val[--sp];
        else {
    	fprintf(stderr, "ERROR. pop: stack is empty.\n");
    	return 0.;
        }
    }
    
    element dup(void) {
        if (sp > 0)
    	return val[sp-1];
        else {
    	fprintf(stderr, "ERROR. pop: stack is empty.\n");
    	return 0.;
        }
    }
    
    void down(void) {
        int i;
        element z;
        z = val[0];
        for (i=0; i<sp; ++i)
    	val[i] = val[i+1];
        val[sp-1] = z;
    }
    
    void up(void) {
        int i;
        element z;
        z = val[sp-1];
        for (i=sp-1; i>0; --i)
    	val[i] = val[i-1];
        val[0] = z;
    }
    
    void list(void) {
        int i;
        for (i=sp-1; i>=0; --i)
    	printf("\t%.8g\n", val[i]);
    }
    
    void swaptop(void) {
        element z;
        if (sp > 1) {
    	z = val[sp-1];
    	val[sp-1] = val[sp-2];
    	val[sp-2] = z;
        }
        else
    	fprintf(stderr, "ERROR. swaptop: not enough in stack.\n");
    }
    

    Created: Nov 26, 1994
    Last Revised: Dec 6, 1994
    © Copyright 1994 Wei-Chang Shann

    shann@math.ncu.edu.tw