两栈共享空间
枚举类型:
enum flag{left,right};
cout<<sizeof(flag)<<endl;//4
flag a;//a=0;//error C2440: “=”: 无法从“int”转换为“wmain::flag”
a=left; //right
cout<<a<<endl;//0
a=flag(0);//right
cout<<sizeof(flag)<<endl;//4
flag a;//a=0;//error C2440: “=”: 无法从“int”转换为“wmain::flag”
a=left; //right
cout<<a<<endl;//0
a=flag(0);//right
栈满
栈1空:top1==-1
栈2空:top2==Stack_size
栈满:top1+1==top2
const int Stack_Size=100;
enum flag{left,right};
template <class T>
class BothStack
{
public:
BothStack( );
~BothStack( );
void Push(int i, T x);
T Pop(int i);
T GetTop(int i);
bool isEmpty(int i)const{//i==0||i==1
assert(i==0||i==1);
if(i==0)
return top1==-1?true:false;
else
return top2==Stack_Size?true:false;
}
bool isFull()const{
return top1+1==top2?true:false;
}
private:
T data[Stack_Size];
int top1, top2;
flag f;
};
//data[0Stack_size-1],则空栈是-1和Stack_size
template<class T>
BothStack<T>::BothStack()
{
top1=-1; //栈1为空栈
top2=Stack_size;//栈2为空栈
}
/*注意:这里的i只能取值为0或1*/
template<class T>
void BothStack<T>::Push(int i, T x)
{
assert(i==0||i==1);
assert(!isFull());
f=flag(i);
//在栈1中压栈
if(f==left)
data[++top1]=x;
else
data[--top2]=x;
}
template<class T>
T BothStack<T>::Pop(int i)
{
assert(i==0||i==1);
assert(!isEmpty(i));
f=flag(i);
if(f==left)
return data[top1--];
else
return data[top2++];
}
template<class T>
T BothStack<T>::GetTop(int i)
{
assert(i==0||i==1);
assert(!isEmpty(i));
f=flag(i);
if(f==left)
return data[top1];
else
return data[top2];
}
enum flag{left,right};
template <class T>
class BothStack
{
public:
BothStack( );
~BothStack( );
void Push(int i, T x);
T Pop(int i);
T GetTop(int i);
bool isEmpty(int i)const{//i==0||i==1
assert(i==0||i==1);
if(i==0)
return top1==-1?true:false;
else
return top2==Stack_Size?true:false;
}
bool isFull()const{
return top1+1==top2?true:false;
}
private:
T data[Stack_Size];
int top1, top2;
flag f;
};
//data[0Stack_size-1],则空栈是-1和Stack_size
template<class T>
BothStack<T>::BothStack()
{
top1=-1; //栈1为空栈
top2=Stack_size;//栈2为空栈
}
/*注意:这里的i只能取值为0或1*/
template<class T>
void BothStack<T>::Push(int i, T x)
{
assert(i==0||i==1);
assert(!isFull());
f=flag(i);
//在栈1中压栈
if(f==left)
data[++top1]=x;
else
data[--top2]=x;
}
template<class T>
T BothStack<T>::Pop(int i)
{
assert(i==0||i==1);
assert(!isEmpty(i));
f=flag(i);
if(f==left)
return data[top1--];
else
return data[top2++];
}
template<class T>
T BothStack<T>::GetTop(int i)
{
assert(i==0||i==1);
assert(!isEmpty(i));
f=flag(i);
if(f==left)
return data[top1];
else
return data[top2];
}