一个数组实现两个栈
2015-11-06 16:59
330 查看
#include<iostream> using namespace std; #define LEFT 0 #define RIGHT 1 template<class T> class DynamicArr { template<class T> friend class Stack; public: DynamicArr(T* data = NULL) :_capacity(3) ,_data(new T[_capacity]) ,_Left(0) //_LEFT表示左栈下一个存储数据的数组下标 ,_Right(1) //_RIGHT表示右栈下一个存储数据的数组下标 ,_size(0) {} ~DynamicArr() { if (_data) { delete[] _data; } } void CheekCapacity() { //左栈或者右栈任何一个下标超出了数组的容量就要扩容 if (_Left >= _capacity || _Right >= _capacity) { _capacity *= 2; T* tmp = new T[_capacity]; memcpy(tmp, _data, sizeof(T)*_capacity); delete[] _data; _data = tmp; } } private: size_t _capacity; T* _data; int _Left; int _Right; size_t _size; }; template<class T> class Stack { DynamicArr<int> d; public: Stack() {} void Push(const T& x,int which) { d.CheekCapacity(); if (which == 0) { d._data[d._Left] = x; d._Left += 2; } if (which == 1) { d._data[d._Right] = x; d._Right += 2; } d._size++; } void Pop(int which) { if (!Empty(which) && which == 0) { d._Left -= 2; } if (!Empty(which) && which == 1) { d._Right -= 2; } d._size--; } int Size(int which) { if (!Empty(which) && which == 0) { return d._Left / 2; } if (!Empty(which) && which == 1) { return (d._Right - 1) / 2; } } bool Empty(int which) { if (which == 0 && d._Left < 0) { return true; } if (which == 1 && d._Right < 0) { return true; } return false; } T& Top(int which) { if (!Empty(which) && which == 0) { return d._data[d._Left - 2]; } if (!Empty(which) && which == 1) { return d._data[d._Right - 2]; } } void Print(int which) { if (!Empty(which) && which == 0) { int i = 0; while( i < d._Left) { cout << d._data[i] << "-"; i += 2; } } if (!Empty(which) && which == 1) { for (int i = 1; i < d._Right; i++) { cout << d._data[i] << "-"; i++; } } cout << endl; } }; int main() { Stack<int> s; s.Push(1, LEFT); s.Push(4, LEFT); s.Push(3, LEFT); s.Push(3, LEFT); s.Push(4, LEFT); s.Print(LEFT); s.Size(LEFT); s.Push(1, RIGHT ); s.Push(2, RIGHT); s.Top(LEFT); s.Size(RIGHT); s.Push(3, RIGHT); s.Top(RIGHT); s.Print(RIGHT); s.Pop(LEFT); s.Pop(RIGHT); getchar(); return 0; }
相关文章推荐
- 如何检测硬盘坏道
- 【转】根据两点经纬度计算距离
- C#系统缓存全解析
- angularjs页面显示表达式问题
- Java编程中的异常和错误你遇到过哪些?
- CentOS6.6安装Oracle 11.2g
- 一个关于AVPlayer蛋疼的释放问题(iOS 9.0 AVPlayer的使用与内存的释放问题)
- Android Fragment学习
- 如何终止冻结的虚拟机
- 编译PROJ4
- 队列汇总
- ARMv8 Fast Models 安装 SierraTEE
- GlusterFS技术交流 QQ群
- 数据驱动测试之—— Excel+TestNG
- <iOS>NSScanner类的基本用法
- ubuntu关于pam_tally2计数器在每次sudo时都增加的bug
- 前端基础2
- expect
- [LeetCode] Valid Parentheses
- leetcode121 Best Time to Buy and Sell Stock