/* * stack.c * Copyright (C) Achille Braquelaire (achille@labri.fr). * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, * USA. */ #include #include #include #include "allocate.h" #include "vector.h" #include "stack.h" struct stack { vector tab; long top; }; stack stackCreate (long length) { ALLOCATE (stack, s); s->tab = vectorCreate (length); s->top = -1; return s; } void stackFree (stack s) { vectorFree (s->tab); free (s); } void stackPush (stack s, void* val) { if (s == NULL) { fprintf (stderr, "stack: null stack argument\n"); exit (EXIT_FAILURE); } s->top = s->top + 1; vectorWrite (s->tab, s->top, val); } void* stackPop (stack s) { if (s == NULL) { fprintf (stderr, "stack: null stack argument\n"); exit (EXIT_FAILURE); } if (stackEmpty (s)) { fprintf (stderr, "stack: cannot pop an empty stack\n"); exit (EXIT_FAILURE); } s->top = s->top - 1; return vectorRead (s->tab, s->top+1); } void* stackTop (stack s) { if (s == NULL) { fprintf (stderr, "stack: null stack argument\n"); exit (EXIT_FAILURE); } if (stackEmpty (s)) { fprintf (stderr, "stack: cannot recover the top of an empty stack\n"); exit (EXIT_FAILURE); } return vectorRead (s->tab, s->top); } int stackEmpty (stack s) { if (s == NULL) { fprintf (stderr, "stack: null stack argument\n"); exit (EXIT_FAILURE); } return (s->top == -1); }