File: dstack.cpp

package info (click to toggle)
openssn 1.4-3
  • links: PTS, VCS
  • area: main
  • in suites: buster, sid
  • size: 7,340 kB
  • sloc: cpp: 10,973; makefile: 80
file content (106 lines) | stat: -rw-r--r-- 2,039 bytes parent folder | download | duplicates (3)
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// $Id: dstack.cpp,v 1.4 2003/04/14 05:51:03 mbridak Exp $
// Simple Stack Class                 

#include <stdio.h>
#include <stdlib.h>
#include "dstack.h"

DStack::DStack()               
{                                  
   bottom_ = NULL;
   top_ = NULL;
   number_items = 0;
}

DStack::~DStack()                   // how to reclaim memory from local
{                                   //   stacks when exiting functions
   clear_stack(); 
}


// erase any/all items on the stack
void DStack::clear_stack()
{
   STACKVALUE *current, *next_value;
   current = bottom_;
   while (current)
   {
       next_value = (STACKVALUE *) current->next;
       free(current);
       current = next_value;
   }

   bottom_ = top_ = NULL;
   number_items = 0;
}


int DStack::num_items()        // number of items currently in stack
{
    return number_items;
}

int DStack::push(float val)        // push a new value 
{
    STACKVALUE *new_value;

    new_value = (STACKVALUE *) calloc(1, sizeof(STACKVALUE));
    if (! new_value)
      return FALSE;
    new_value->value = val;
    if (top_)
    {
        top_->next = new_value;
        new_value->previous = top_;
        top_ = new_value;
    }
    else   // no values exist
    {
      bottom_ = top_ = new_value;
    }
    number_items++;
    return TRUE;
}

float DStack::pop()                 // pop value from top
{
   float my_return = 0.0;
   STACKVALUE *new_top = NULL;

   if (top_)
   {
      my_return = top_->value;
      new_top = (STACKVALUE *) top_->previous; 
      free(top_);
      top_ = new_top;
      number_items--;
      if (! top_)
        bottom_ = NULL;
   }
   return my_return;
}



int DStack::empty()           // 1 if empty, 0 otherwise
{
   if (number_items)
      return FALSE;
   else
      return TRUE; 
}



void DStack::print()
{
   STACKVALUE *current;
   printf("Stack holds %d items.\n", number_items);
   current = bottom_;
   while (current)
   {
       printf("Value: %f\n", current->value);
       current = (STACKVALUE *) current->next;
   }
}