1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
|
/***********************************************************************
* Code listing from "Advanced Linux Programming," by CodeSourcery LLC *
* Copyright (C) 2001 by New Riders Publishing *
* See COPYRIGHT for license information. *
***********************************************************************/
/* Provide a stack of "number"s. */
#include <assert.h>
#include <stdlib.h>
#include "definitions.h"
/* Create an empty stack. */
Stack create_stack ()
{
return 0;
}
/* Return nonzero if the stack is empty. */
int empty_stack (Stack stack)
{
return stack == 0;
}
/* Remove the number at the top of a non-empty stack. If the stack is
empty, abort. */
number pop_stack (Stack* stack)
{
number answer;
Stack rest_of_stack;
assert (!empty_stack (*stack));
answer = (*stack)->element_;
rest_of_stack = (*stack)->next_;
free (*stack);
*stack = rest_of_stack;
return answer;
}
/* Add a number to the beginning of a stack. */
void push_stack (Stack* stack, number n)
{
Stack new_stack = malloc (sizeof (struct StackElement));
new_stack->element_ = n;
new_stack->next_ = *stack;
*stack = new_stack;
}
/* Remove all the stack's elements. */
void clear_stack (Stack* stack)
{
while (!empty_stack (*stack)) {
number top = pop_stack (stack);
destroy_number (top);
}
}
|