在数组的两端存放两个栈

将数组的起始位置看作是一个栈的栈底,将数组的尾部看作是另一个栈的栈底,压栈时,栈顶指针分别向中间移动,只要两栈顶指针不相遇,两个栈就可以一直使用,当两个指针相遇时,数组除指针所指位置外,其余地方都已经被装满数据。当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;
}


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值