#include<iostream>
#include<stdlib.h>
using namespace std;
template <class elemtype>
class stack {
public:
virtual bool is_empty() const = 0;
virtual void push(const elemtype &x) = 0;
virtual elemtype pop() = 0;
virtual elemtype top() const = 0;
virtual ~stack() {}
};
template <class elemtype>
class set_stack: public stack <elemtype> {
private:
elemtype *elem;
int top_p;
int max_size;
void double_space();
public:
set_stack(int init_size = 10) {
elem = new elemtype [init_size];
max_size = init_size;
top_p = -1;
}
~set_stack() { delete[] elem; }
bool is_empty() const { return top_p == -1; }
void push(const elemtype &x) {
if(top_p == max_size - 1) {
double_space();
}
elem[++top_p] = x;
}
elemtype pop() {
return elem[--top_p];
}
elemtype top() const {
return elem[top_p];
}
};
template <class elemtype>
void set_stack<elemtype>::double_space(){
elemtype *tmp = elem;
elem = new elemtype[2*max_size];
for(int i = 0; i < max_size; ++i) {
elem[i] = tmp[i];
}
max_size *= 2;
delete[] tmp;
};
int main()
{
set_stack<int> *s = new set_stack<int>(10);
cout<<s->is_empty();
// s->push(3);
for(int i = 1; i <= 20; i++) {
s->push(i*10);
}
for(int i = 1; i <=20 ; i++) {
cout << s->top() << endl;
s->pop();
}
cout<<s->top();
return 0;
}
//这道题目的意义重大,标志我要全面学习C++了!呵呵,加油。
栈的基本操作(C++)
最新推荐文章于 2024-09-30 18:37:43 发布