STL的简单实现(一) 栈

目前暂不支持动态大小,支持指定大小与默认大小,主要包含元素的插入,栈顶的访问与弹出,首尾地址的获取

/* 模拟栈的基本实现*/
#ifndef __stack__
#define __stack__
#include <iostream>
using namespace std;
#include<iostream>
#include<cstdlib>
using namespace std;
template<class type>
class STACK {
private:
 int top;
 int max;
 type *stack;
public:
 STACK();
 STACK(int n);
 ~STACK();
 type pop();   //弹出栈顶元素
 type front();  //访问栈顶元素
 void insert(type num);  //插入元素
 int size();   //元素个数
 void clear();   //清理栈
 bool empty();   //判断空栈
};
template<class type>
STACK<type>::STACK(int n) {
 max = n;
 stack = new type[n];
 top = -1;
 memset(stack, 0, max * sizeof(type));
}
template<class  type>
STACK<type>::STACK() {
 max = 512;
 stack = new type[512];
 top = -1;
 memset(stack, 0, 512 * sizeof(type));
}
template<class type>
STACK<type>::~STACK() {
 if (stack == NULL) { cout << "已为空栈\n"; return; }
 delete[] stack;  cout << "栈已清除\n"; stack = NULL;
}
template<class type>
type STACK<type>::pop() {
 if (stack == NULL) { cout << "shit 栈已清除\n"; return 0; }
 if (top == -1) { cout << "栈为空   返回一个零 "; return 0; }
 top--;
 return stack[top + 1];
}
template<class type>
type STACK<type>::front() {
 if (stack == NULL) { cout << "shit 栈已清除\n"; return 0; }
 if (top == -1) { cout << "栈为空   返回一个零 "; ; return 0; }
 return stack[top];
}
template<class type>
void STACK<type>::insert(type num) {
 if (stack == NULL) { cout << "shit 栈已清除\n"; return; }
 if (top == max - 1) { cout << "栈已满" << endl;; return; }
 cout << "insert stack successful  the num is " << num << endl;
 stack[++top] = num;
}
template<class type>
int STACK<type>::size() {
 if (stack == NULL) { cout << "shit 栈已清除\n"; return 0; }
 return top + 1;
}  //栈的元素个数
template<class type>
bool STACK<type>::empty() {
 if (top == -1) return true; return false;
}
template<class type>
void STACK<type>::clear() {
 delete[] stack;
 cout << "栈已清除\n";
 stack = NULL;
 top = -1;
 memset(stack, 0, n*sizeof(type);
}



#endif //stack

功能相对简陋,有改进的意见,欢迎各路大神提出.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值