泛型编程实现堆栈

泛型编程实现堆栈

#ifndef _STACK_H_

#define _STACK_H_
#include <cstdlib>
#include <iostream>
using namespace std;
const int STACK_INIT_SIZE = 1;
const int ADD_SIZE = 10;
template<typename T>
class Stack
{
public:
Stack();
~Stack();
void Destroy();
void Clear();
int Length();
void Top(T &e);
void Pop(T &e);
void Push(const T &e);
bool IsEmpty();
private:
T* base;
T* top;
int size;
};


#endif
template<typename T>
Stack<T>::Stack()
{
base = (T*)malloc(STACK_INIT_SIZE * sizeof(T));
if (!base)
{
cout << "statck init error" << endl;
return;
}
top = base;
size = STACK_INIT_SIZE;
}


template<typename T>
Stack<T>::~Stack()
{
Destroy();
}


template<typename T>
void Stack<T>::Destroy()
{
free(base);
top = nullptr;
base = nullptr;
size = 0;
}


template<typename T>
void Stack<T>::Clear()
{
top = base;
}


template<typename T>
int Stack<T>::Length()
{
return top - base;
}


template<typename T>
void Stack<T>::Top(T &e)
{
if (top > base)
{
e = *(top - 1);
}
else
{
cout << "Top error" << endl;
}
}


template<typename T>
void Stack<T>::Push(const T &e)
{
if (top - base >= size)
{
base = (T*)realloc(base, (size + ADD_SIZE)*sizeof(T));
if (!base)
{
cout << "realloc error" << endl;
}
top = base + size;
size += ADD_SIZE;
}
*(top)++ = e;
}


template<typename T>
bool Stack<T>::IsEmpty()
{
if (base == top)
{
return true;
}
return false;
}


template<typename T>
void Stack<T>::Pop(T &e)
{
if (top > base)
{
e = *(--top);
}
else
{
cout << "Pop error" << endl;
}

}

测试

#include "Stack.h"
#include <iostream>
using namespace std;
int main()
{
Stack<double> stack;
double x;
while (cin >> x)
{
if (x == 999)
{
break;
}
stack.Push(x);
}
cout << "length:" << stack.Length() << endl;
double e;
stack.Top(e);
cout << "top:" << e << endl;
while (!stack.IsEmpty())
{
stack.Pop(e);
cout << e << " ";
}
cout << endl;
stack.Top(e);
cin >> x;
return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值