Stack as ex3.1
This commit is contained in:
parent
b313ad8364
commit
91a78e2d74
2 changed files with 50 additions and 54 deletions
|
@ -1,57 +1,26 @@
|
|||
//Stack.cc
|
||||
#include <iostream>
|
||||
using namespace std ;
|
||||
#include "Stack.hh"
|
||||
|
||||
const int LEN = 80 ; // default stack length
|
||||
|
||||
struct Stack {
|
||||
// Implementation
|
||||
double s[LEN] ;
|
||||
int count ;
|
||||
|
||||
// Interface
|
||||
void init() { count = 0 ; }
|
||||
int nitems() { return count ; }
|
||||
bool full() { return (count==LEN) ; }
|
||||
bool empty() { return (count==0) ; }
|
||||
|
||||
void push(double c) {
|
||||
void Stack::push(double c) {
|
||||
if (full()) {
|
||||
cout << "Stack::push() Error: stack is full" << endl ;
|
||||
std::cout << "Stack::push() Error: stack is full" << std::endl ;
|
||||
return ;
|
||||
}
|
||||
s[count++] = c ;
|
||||
}
|
||||
|
||||
double pop() {
|
||||
double Stack::pop() {
|
||||
if (empty()) {
|
||||
cout << "Stack::pop() Error: stack is empty" << endl ;
|
||||
std::cout << "Stack::pop() Error: stack is empty" << std::endl ;
|
||||
return 0 ;
|
||||
}
|
||||
return s[--count] ;
|
||||
}
|
||||
} ;
|
||||
|
||||
|
||||
int main() {
|
||||
|
||||
Stack s ;
|
||||
s.init() ; // initialize Stack
|
||||
|
||||
// Write doubles into Stack
|
||||
int i ;
|
||||
for (i=0 ; i<10 ; i++) {
|
||||
cout << "pushing value " << i*i << " in stack" << endl ;
|
||||
s.push(i*i) ;
|
||||
void Stack::inspect() {
|
||||
for ( int i = nitems() - 1; i >= 0; i-- )
|
||||
{
|
||||
std::cout << i << ": " << s[i] << std::endl;
|
||||
}
|
||||
|
||||
// Count doubles in fifo
|
||||
cout << s.nitems() << " value in stack" << endl ;
|
||||
|
||||
// Read doubles back from fifo
|
||||
while (!s.empty()) {
|
||||
double val = s.pop() ;
|
||||
cout << "popping value " << val << " from stack" << endl ;
|
||||
}
|
||||
|
||||
return 0 ;
|
||||
}
|
||||
|
|
27
Stack/Stack.hh
Normal file
27
Stack/Stack.hh
Normal file
|
@ -0,0 +1,27 @@
|
|||
//Stack.h
|
||||
|
||||
#ifndef STACK_H
|
||||
#define STACK_H
|
||||
|
||||
const int LEN = 80 ; // default stack length
|
||||
class Stack {
|
||||
// Interface
|
||||
public:
|
||||
Stack() { init(); }
|
||||
~Stack() {}
|
||||
int nitems() { return count ; }
|
||||
bool full() { return (count==LEN) ; }
|
||||
bool empty() { return (count==0) ; }
|
||||
|
||||
void push( double c );
|
||||
double pop();
|
||||
void inspect();
|
||||
|
||||
// Implementation
|
||||
private:
|
||||
void init() { count = 0 ; }
|
||||
double s[LEN] ;
|
||||
int count ;
|
||||
|
||||
};
|
||||
#endif
|
Reference in a new issue