SeqStack.h
#ifndef SEQSTACK_H
#define SEQSTACK_H
#include<iostream>
int default_size = 20;
// SeqStack
template<typename T>
class SeqStack{
public:
typedef T& reference;
SeqStack(int size = default_size);//constructor
~SeqStack();//destructor
void push(const T value);//push
void pop();//pop
reference get_top();//top
bool empty();//whether stack is empty or not
int size();//get length
private:
void renew(int size);//realloc stack size
private:
T* base;
T* top;
int stack_size;
};
//constructor
template<typename T>
SeqStack<T>::SeqStack(int size){
if (size > 0){
base = new T[size];
stack_size = size;
}
else{
base = new T[default_size];
stack_size = default_size;
}
top = base;
}
//destructor
template<typename T>
SeqStack<T>::~SeqStack(){
delete[] base;
base = NULL;
top = NULL;
stack_size = 0;
}
//push
template<typename T>
void SeqStack<T>::push(const T value){
if (top - base >= stack_size){
renew(stack_size + default_size);
stack_size += default_size;
}
*top = value;
top++;
}
//pop
template<typename T>
void SeqStack<T>::pop(){
if (empty()){
std::cout << "there is no element in stack" << std::endl;
exit(1);
}
top--;
}
//top
template<typename T>
typename SeqStack<T>::reference SeqStack<T>::get_top(){
if (empty()){
std::cout << "there is no element in stack" << std::endl;
exit(1);
}
return *(top-1);
}
//whether stack is empty or not
template<typename T>
bool SeqStack<T>::empty(){
if (top == base)
return true;
return false;
}
//get length
template<typename T>
int SeqStack<T>::size(){
return top - base;
}
//realloc stack size
template<typename T>
void SeqStack<T>::renew(int size){
T* p = base;
base=new T[size];
for (int i = 0; i < stack_size; i++){
base[i] = p[i];
}
top = base + stack_size;
delete[] p;
}
#endif
main.cpp
#include"SeqStack.h"
using namespace std;
int main(){
SeqStack<int> int_stack;
cout << int_stack.size() << endl; //0
cout << boolalpha << int_stack.empty() << endl;//true
for (int i = 0; i < 20; i++){
int_stack.push(i);
}
cout << int_stack.size() << endl; //20
cout << int_stack.get_top() << endl;//19
cout << boolalpha << int_stack.empty() << endl;//false
int_stack.push(21);
cout << int_stack.get_top() << endl;//21
int_stack.pop();
cout << int_stack.get_top() << endl;//19
int_stack.pop();
int_stack.push(22);
cout << int_stack.size() << endl; //20
cout << int_stack.get_top() << endl;//22
int_stack.pop();
cout << int_stack.get_top() << endl;//18
return 0;
}