//---------------------------------------------------------------- // // basic-stack.cpp // // Implements a simple character stack Based on the example // from Pohl, C++ by Dissection, pages 187-191 // // written by: Simon Parsons // modified : 22nd February 2009 // //---------------------------------------------------------------- #include #include using namespace std; //---------------------------------------------------------------- // // charStack // charStack implements a stack of characters. A stack is a data structure // into which data, in this case characters, can be "push"ed, and out of // which they may be "pop"ed. // Just like a Pez dispensor :-) // The private data members are the stack itself, which is just an array // and the number of the "top" element in the array. // // The public function members allow items in the stack to be manipulated. // // The class definition includes an internal enum that (hopefully) makes // some of the operations a bit clearer. class charStack { private: enum{EMPTY = -1, maxLen = 100, FULL = maxLen -1}; char stack[maxLen]; int top; public: void reset(); void push(char); char pop(); char topOfStack() const; bool isEmpty() const; bool isFull() const; }; // reset // // Reset the stack. We don't change what is in it, we just forget that // anything is in there. void charStack::reset() { top = EMPTY; } // push // // Push an item onto the stack. We actually write it into the next element // of the array, adjusting the value of top, which tells us which the top // element is. // // Note that ++top increments top before we write the new value into the // array. void charStack::push(char c) { stack[++top] = c; } // pop // // Remove an element from the top of the stack. We do this by first reading // out the top element and then reducing the value of top, combining these // operations by the use of top--. char charStack::pop() { return stack[top--]; } // topOfStack // // Return the value at the top of the stack without removing it from the // stack. char charStack::topOfStack() const { return stack[top]; } // isEmpty // // Return true if there is nothing in the stack, false otherwise. bool charStack::isEmpty() const { return (top == EMPTY); } // isFull // // Return true the stack is full, false otherwise. bool charStack::isFull() const { return (top == FULL); } //---------------------------------------------------------------- // // Main program // Creates a stack, pushing a string into it, character by character // and then poping them out, reversing the string. int main() { charStack s; string str = "hello world"; int i = 0; cout << "string = " << str << endl; s.reset(); while(str[i] && ! s.isFull()) { s.push( str[i++] ); } cout << "reversed string= "; while (! s.isEmpty() ) { cout << s.pop(); } cout << endl; }