一、两栈的定义
演示使用了乘2,表示一个栈占10个空间,两个占20
class DoubleStack
{
public:
DoubleStack(int len)
{
this->m_Array = new int[len * 2]{};
this->m_Idx_One = -1;
this->m_Idx_Two = len * 2;
this->m_Len = len * 2;
}
void Push(int StackNum, int data);
void Pop(int StackNum);
void Print();
~DoubleStack()
{
if (this->m_Array != nullptr)
{
delete[] this->m_Array;
this->m_Array = nullptr;
}
}
private:
int m_Idx_One;
int m_Idx_Two;
int m_Len;
int* m_Array;
};
二、进栈
void DoubleStack::Push(int StackNum, int data)
{
if (this->m_Idx_One + 1 == this->m_Idx_Two)
{
cout << "栈已满" << endl;
}
if (StackNum == 1)
{
this->m_Array[++this->m_Idx_One] = data;
}
else if (StackNum == 2)
{
this->m_Array[--this->m_Idx_Two] = data;
}
}
三、出栈
void DoubleStack::Pop(int StackNum)
{
if (StackNum == 1)
{
if (this->m_Idx_One == -1)
{
cout << "栈1为空栈,删除错误" << endl;
}
this->m_Array[this->m_Idx_One--] = 0;
}
else if (StackNum == 2)
{
if (this->m_Idx_Two == this->m_Len)
{
cout << "栈2为空栈,删除错误" << endl;
}
this->m_Array[this->m_Idx_Two++] = 0;
}
}
四、整体展示
#include <iostream>
using namespace std;
class DoubleStack
{
public:
DoubleStack(int len)
{
this->m_Array = new int[len * 2]{};
this->m_Idx_One = -1;
this->m_Idx_Two = len * 2;
this->m_Len = len * 2;
}
void Push(int StackNum, int data);
void Pop(int StackNum);
void Print();
~DoubleStack()
{
if (this->m_Array != nullptr)
{
delete[] this->m_Array;
this->m_Array = nullptr;
}
}
private:
int m_Idx_One;
int m_Idx_Two;
int m_Len;
int* m_Array;
};
void DoubleStack::Push(int StackNum, int data)
{
if (this->m_Idx_One + 1 == this->m_Idx_Two)
{
cout << "栈已满" << endl;
}
if (StackNum == 1)
{
this->m_Array[++this->m_Idx_One] = data;
}
else if (StackNum == 2)
{
this->m_Array[--this->m_Idx_Two] = data;
}
}
void DoubleStack::Pop(int StackNum)
{
if (StackNum == 1)
{
if (this->m_Idx_One == -1)
{
cout << "栈1为空栈,删除错误" << endl;
}
this->m_Array[this->m_Idx_One--] = 0;
}
else if (StackNum == 2)
{
if (this->m_Idx_Two == this->m_Len)
{
cout << "栈2为空栈,删除错误" << endl;
}
this->m_Array[this->m_Idx_Two++] = 0;
}
}
void DoubleStack::Print()
{
for (int i = 0; i <= this->m_Len - 1; ++i)
{
cout << this->m_Array[i] << " ";
}
cout << endl;
}
void Text()
{
DoubleStack ds(10);
ds.Push(1, 10);
ds.Push(2, 10);
ds.Push(1, 10);
ds.Push(2, 10);
ds.Push(1, 10);
ds.Print();
ds.Pop(1);
ds.Pop(2);
ds.Print();
}
int main()
{
Text();
system("pause");
return 0;
}