将数组的起始位置看作是一个栈的栈底,将数组的尾部看作是另一个栈的栈底,压栈时,栈顶指针分别向中间移动,只要两栈顶指针不相遇,两个栈就可以一直使用,当两个指针相遇时,数组除指针所指位置外,其余地方都已经被装满数据。当top1=投票+1时,数组需要进行扩容处理。
#include<iostream>
class AStack
{
public:
AStack()
{
arryCapcity =0;
top1 = top2 = 0;
listArray = NULL;
}
~AStack()
{
delete[] listArray;
}
void clear() { top1 = top2 = 0; }
void pushAStack1(const int& it)
{
checkCapcity();
listArray[top1++] = it;
}
void pushAStack2(const int& it)
{
checkCapcity();
listArray[top2--] = it;
}
int popAStack1()
{
checkCapcity();
return listArray[--top1];
}
int popAStack2()
{
checkCapcity();
return listArray[++top2];
}
const int& top1Value()const
{
if (arryCapcity==0)
{
std::cout << "数组中存储了两个空栈!" << std::endl;
return -1;
}
else
{
if (top1 == 0)
{
std::cout << "数组中存储了两个空栈!" << std::endl;
return -1;
}
else
{
return listArray[top1 - 1];
}
}
}
const int& top2Value()const
{
if (arryCapcity == 0)
{
std::cout << "数组中存储了两个空栈!" << std::endl;
return -1;
}
else
{
if (top2 == arryCapcity-1)
{
std::cout << "数组中存储了两个空栈!" << std::endl;
return -1;
}
else
{
return listArray[top2 + 1];
}
}
}
int lengthTop1() const
{
return top1;
}
int lengthTop2() const
{
return (arryCapcity -1)- top2;
}
void print()
{
if (listArray ==NULL)
{
std::cout << "不存在数组及栈!" << std::endl;
}
else
{
if (lengthTop1() + lengthTop2() <= arryCapcity)
{
for (int i = 0; i < top1; ++i)
{
std::cout << "数组中存放的栈1数值:" << listArray[i] << std::endl;
}
for (int i = arryCapcity - 1; i > top2; --i)
{
std::cout << "数组中存放的栈2数值:" << listArray[i] << std::endl;
}
}
std::cout << "数组的长度:" << arryCapcity << std::endl;
std::cout << "栈1的第一个空闲值top1的值:" << top1 << std::endl;
std::cout << "栈2的第一个空闲值top2的值:" << top2 << std::endl;
}
}
private:
void checkCapcity()
{
if (listArray == NULL)
{
arryCapcity = 3;
listArray = new int[arryCapcity];
top2 = arryCapcity - 1;
return;
}
if (top1 == top2 + 1)//扩容
{
int newCapcity = 2 * arryCapcity;
int* tempArray = new int[newCapcity];
for (int i = 0; i < top1; i++)
{
tempArray[i] = listArray[i];
}
for (int i = arryCapcity - 1,j =newCapcity-1; i > top2; i--,j--)
{
tempArray[j] = listArray[i];
}
delete[] listArray;
listArray = tempArray;
top2 = newCapcity - 1 - ((arryCapcity - 1) - top2);//top2的新位置
arryCapcity = newCapcity;
}
}
private:
int arryCapcity;
int top1, top2;
int* listArray;
};
int main()
{
AStack stack;
stack.pushAStack2(1);
stack.pushAStack2(2);
stack.pushAStack2(5);
stack.pushAStack2(10);
stack.popAStack2();
stack.pushAStack2(36);
stack.pushAStack1(0);
stack.pushAStack1(6);
stack.print();
return 0;
}