用C++实现STL容器stack
2015-10-18 10:53
489 查看
template<class Object> class Stack { public: enum{STACK_SIZE = 20}; Stack(int n = 0):stack_top(0){ theSize = n + STACK_SIZE; st = new Object[theSize]; } ~Stack(){delete [] st;} typedef Object * iterator; typedef const Object * const_iterator; iterator push(const Object & obt){ if (stack_top == theSize-1) { resize(2 * stack_top + 1); } st[stack_top] = obt; stack_top++; return &st[stack_top]; } iterator pop(){ if(empty()){ printf("the stack is empty.\n"); return &st[0]; } stack_top--; return &st[stack_top]; } Object & top() const{ if(empty()){ printf("the stack is empty.\n"); return st[0]; } return st[stack_top-1]; } bool empty() const{ if (stack_top == 0) return true; else return false; } void resize(int newSize){ Object * oldObject = st; st = new Object[newSize]; for (int i = 0; i < stack_top; i++){ st[i] = oldObject[i]; } delete [] oldObject; } int size() const{ return top-1; } private: int stack_top; int theSize; Object * st; };
#include "stack.h" #include <iostream> using namespace std; int main() { Stack<int> s; if (s.empty()) cout << "the stack is empty.\n"; else cout << "the stack is not empty.\n"; s.push(1); s.push(2); s.push(3); s.push(4); if (s.empty()) cout << "the stack is empty.\n"; else cout << "the stack is not empty.\n";; cout << "stack top element is " << s.top() << endl; s.pop(); cout << "After the pop, the top element is " << s.top() << endl; /*判断输入的括号是不是成对出现;输入括号符号,当输入为q或Q的时候退出*/ Stack<char> char_stack; char ch; while(cin >> ch && ch != 'q' && ch != 'Q'){ switch (ch) { case '(': char_stack.push(ch);break; case ')': if (char_stack.top() == '(') char_stack.pop(); else char_stack.push(ch); break; case '[': char_stack.push(ch);break; case ']': if (char_stack.top() == '[') char_stack.pop(); else char_stack.push(ch); break; case '{': char_stack.push(ch);break; case '}': if (char_stack.top() == '{') char_stack.pop(); else char_stack.push(ch); break; default: break; } } if(char_stack.empty()) cout << "the input is right.\n"; else cout << "the input is wrong.\n"; system("pause"); exit(0); }
相关文章推荐
- C++设计模式--享元模式【转载】
- C/C++经典图书推荐
- Merge Two Sorted Lists(C++)
- C语言获取文件大小相关操作
- [黑马训练营]IOS C语言分支语句
- c字符串的处理
- C++堆和栈的比较
- [黑马训练营]IOS C语言运算符
- C语言名题精选百则:所有子集,字典子集,Gray子集
- zerglurker的c语言教程006——第一功能
- 实现一个函数,判断一个数是不是素数。
- 创建一个数组, 实现初始化数组、清空数组、完成数组元素的逆置。
- 实现一个函数判断year是不是闰年。
- 实现一个函数,打印乘法口诀表,口诀表的行数和列数自己指定,输入多少打印几乘几的乘法表
- C语言基础知识
- C++ Primer章课后编程问题
- [c++]LeetCode Median of Two Sorted Arrays问题
- 剑指offer第十八题【二叉树的镜像】c++实现
- Item 41:隐式接口与编译期多态 Effective C++笔记
- 关于C语言中Implicit declaration of function ‘XXXX’ is invalid in C99警告