Stack Implementation in C++
2013-05-31 09:54
239 查看
//Simple implementation #define STACK_CAPACITY 1000 typedef char el_t; // defines the element type el_t to be char for now class Stack { private: // Private data members are: el_t el[STACK_CAPACITY]; // el is an array with slots 0 .. STACK_CAPACITY-1 int topIndex; // the index to the top element public: Stack(); // constructor for a stack void push(el_t); // adds c to the top of the stack void pop(el_t &); // removes top element char top(el_t &); // returns the top element bool isEmpty(); // returns true if the stack is empty ~Stack(); // destructor for a stack }; #include <iostream> using namespace std; #include<string> Stack::Stack() // constructor for a stack { topIndex=-1; } void Stack::push(el_t elem) { if(topIndex<STACK_CAPACITY) { topIndex++; el[topIndex]=elem; } else cout<<"Error: Overflow!"<<endl; } void Stack::pop(el_t &elem) { if (topIndex>-1) { elem=el[topIndex]; topIndex--; } else cout<<"Error: Underflow!"<<endl; } char Stack::top(el_t &elem) { if(isEmpty()) cout<<"Error: Underflow!"<<endl; else elem=el[topIndex]; return elem; } bool Stack::isEmpty() { if (topIndex==-1) return true; else return false; } Stack::~Stack() { /* nothing to do*/ } int main() { Stack mystack; string s; char b; cout<<"character string? (end with ^Z to quit)" <<endl; //to inform the user to input string. while(cin>>s) { for(int i=0;i<s.length();i++) { mystack.push(s[i]); } } cout<<"character removed from the stack is: "<<endl; while(!mystack.isEmpty()) { mystack.pop(b); cout<<b<<endl; } cout<<endl; system("pause"); return 0; }
相关文章推荐
- Fast implementation/approximation of pow() function in C/C++
- comment:Yet Another Generalized Functors Implementation in C++
- stack in c++
- A simple implementation of string split in C++
- Binary Tree Inorder Traversal 二叉树的中序遍历(C++:Iterative solution using stack)
- noncopyable implementation in C++
- c++ why can't class template hide its implementation in cpp file?
- IPSec Implementation in Linux Kernel Stack
- How to separate the implementation and definition for template function in c++
- An implementation of the skip list data structure written in C++
- An AES (Rijndael) Implementation in C/C++ (as specified in FIPS-197)
- Stack & Heap in C/C++
- Advanced Run Time Type Identification in C++ Part II(Property Library An Implementation of RTTI in C++)
- A design & implementation of reflection in C++
- A design & implementation of reflection in C++
- Stack & Heap in C/C++ .
- 【ThinkingInC++】34、带有构造函数和析构函数的Stack
- How do you copy the contents of an array to a std::vector in C++ without looping? (From stack over flow)
- Stack ---- Implementation in C and Python
- 想翻译Memory Management Algorithms and Implementation in c/c++