您的位置:首页 > 其它

一个数组实现两个栈

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: