1.元素出栈、入栈顺序的合法性。如入栈的序列(1,2,3,4,5),出栈序列为(4,5,3,2,1)
思路:
1.将序列存入数组,刚开始栈空将序列中第一个元素入栈,数组下标向后移
2.判断栈顶元素与出栈序列是否相等,相等将栈顶元素Pop,出栈序列下标后移。不相等重复1.2
3.循环1,2直到遍历超出入栈序列范围返回不合法,或者出栈序列遍历完返回合法
代码:
int IsStackValidOrder(int *InArr, int Insize, int *outArr, int outsize)
{
Stack s;
int InIdx = 0;
int outIdx = 0;
assert(InArr);
assert(outArr);
StackInit(&s);
if (Insize != outsize)
return -1;
while (outIdx < outsize)
{
while (StackNum(&s) == 0 || StackTop(&s) != outArr[outIdx])
{
if (InIdx == Insize)
return -1;
StackPush(&s, InArr[InIdx++]);
//InIdx++;
}
StackPop(&s);
outIdx++;
}
return 1;
}
2.一个数组实现两个栈(共享栈)
思路:
创建一个结构体,成员包括一个数组,两个下标,
初始化让两个下标分别指向数组的首地址和末地址
两个下标同时分别作为两个栈的栈顶下标,向中间入栈
当lift下标>right下标表示数组满,
typedef struct ShareStackByArr
{
int Arr[max];
int S1;
int S2;
}ShareStackByArr;
void ShareStackByArrInit(ShareStackByArr* p);//初始化
void ShareStackByArrPush(ShareStackByArr* p, DataType data, int which);//入栈
int ShareStackByArrPop(ShareStackByArr* p, int which);//出栈
DataType ShareStackByArrTop(ShareStackByArr* p, int which);//取栈顶元素
int ShareStackByArrSize(ShareStackByArr* p, int which);//求栈大小
int ShareStackByArrEmpty(ShareStackByArr* p, int which);//栈是否空
void ShareStackByArrInit(ShareStackByArr* p)
{
assert(p);
p->S1 = 0;
p->S2 = max - 1;
}
void ShareStackByArrPush(ShareStackByArr* p, DataType data,int which)
{
assert(p);
if (p->S1 > p->S2)
{
printf("栈满\n");
return 0;
}
if (1 == which)
{
p->Arr[p->S1++] = data;
}
else
{
p->Arr[p->S2--] = data;
}
}
int ShareStackByArrPop(ShareStackByArr* p, int which)
{
assert(p);
if (1 == which && p->S1 > 0)
{
p->S1--;
}
if(2 == which && p->S2 < max - 1)
p->S2++;
}
DataType ShareStackByArrTop(ShareStackByArr* p, int which)
{
int n = 0;
assert(p);
if (1 == which && p->S1 > 0)
{
n = p->S1;
return p->Arr[--n];
}
if (2 == which && p->S2 < max - 1)
{
n = p->S2;
return p->Arr[++n];
}
}
int ShareStackByArrSize(ShareStackByArr* p, int which)
{
assert(p);
if (1 == which)
return p->S1;
if (2 == which)
return max - (p->S2) - 1;
}
int ShareStackByArrEmpty(ShareStackByArr* p, int which)
{
assert(p);
return !ShareStackByArrSize(p, which);
}