Debian Codegraph @

listings/appendix-a/stack.c

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