Ex 3.2: Dynamic Stack
This commit is contained in:
parent
91a78e2d74
commit
fa61fdaf21
5 changed files with 157 additions and 7 deletions
|
@ -5,7 +5,8 @@
|
|||
void Stack::push(double c) {
|
||||
if (full()) {
|
||||
std::cout << "Stack::push() Error: stack is full" << std::endl ;
|
||||
return ;
|
||||
|
||||
grow( DELTA );
|
||||
}
|
||||
s[count++] = c ;
|
||||
}
|
||||
|
@ -24,3 +25,26 @@ void Stack::inspect() {
|
|||
std::cout << i << ": " << s[i] << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
void Stack::init( int in_size ) {
|
||||
bufsize = in_size ;
|
||||
count = 0 ;
|
||||
|
||||
s = new double[in_size];
|
||||
}
|
||||
void Stack::grow( int delta ) {
|
||||
std::cout << "Growing by " << delta << std::endl;
|
||||
double* newbuf = new double[ bufsize + delta ];
|
||||
|
||||
// Copy elements
|
||||
for ( int i=0; i < count ; i++ )
|
||||
{
|
||||
newbuf[i] = s[i];
|
||||
}
|
||||
|
||||
// Delete old Stack
|
||||
delete[] s;
|
||||
|
||||
// Assign pointer
|
||||
s = newbuf;
|
||||
}
|
||||
|
|
|
@ -3,25 +3,32 @@
|
|||
#ifndef STACK_H
|
||||
#define STACK_H
|
||||
|
||||
const int LEN = 80 ; // default stack length
|
||||
const int DELTA = 5 ; // default growing size
|
||||
class Stack {
|
||||
// Interface
|
||||
public:
|
||||
Stack() { init(); }
|
||||
~Stack() {}
|
||||
Stack() { init( DELTA ); }
|
||||
Stack( int in_size ) { init(in_size); }
|
||||
~Stack() {
|
||||
delete[] s;
|
||||
}
|
||||
int nitems() { return count ; }
|
||||
bool full() { return (count==LEN) ; }
|
||||
bool full() { return (count==bufsize) ; }
|
||||
bool empty() { return (count==0) ; }
|
||||
|
||||
void push( double c );
|
||||
double pop();
|
||||
void inspect();
|
||||
|
||||
void grow( int delta );
|
||||
|
||||
// Implementation
|
||||
private:
|
||||
void init() { count = 0 ; }
|
||||
double s[LEN] ;
|
||||
void init( int in_size );
|
||||
|
||||
double* s ;
|
||||
int count ;
|
||||
int bufsize ;
|
||||
|
||||
};
|
||||
#endif
|
||||
|
|
Reference in a new issue