栈的实现
来源:互联网 发布:linux apache cgi 编辑:程序博客网 时间:2024/06/18 04:01
栈比较简单就不说了,这里是用vector实现的,链表的话也差不多。
#ifndef STACK_H#define STACK_H#include <iostream>#include <vector>using namespace std;template<typename Comparable>class stack{public: stack() : topOfStack(-1) {} int size() const { return theArray.size(); } bool isEmpty() const { return *this.size() == 0; } void push(const Comparable & x) { theArray.push_back(x); ++topOfStack; } Comparable pop() { --topOfStack; theArray.pop_back(); return theArray.back(); } Comparable top() const { return theArray.back(); }private: vector<int> theArray; int topOfStack;};#endif // STACK_H
测试
#include "stack.h"int main(int argc, char *argv[]){ stack<int> test; for(int i = 0; i < 10; ++i) test.push(i); cout << "长度:" << test.size() << endl; cout << "栈顶元素:" << test.top() << endl; test.pop(); cout << "长度:" << test.size() << endl; cout << "栈顶元素:" << test.top() << endl; return 0;}
0 0