元素出栈、入栈顺序的合法性【数据结构】

元素出栈、入栈顺序的合法性。如入栈的序列(1,2,3,4,5),出栈序列为(4,5,3,2,1)。

Test.c

int TestStackInAndOutValid(int* In, int InSize, int* Out, int OutSize)
{
	Stack s;
	int InIndex = 0;
	int OutIndex = 0;
	//入栈次序的大小和出栈的不相等 ,返回
	InitStack(&s);
	if (InSize != OutSize)
	{
		return 0;
	}
	//栈为空,栈顶元素与出栈次序索引标记位置元素值不相等,入栈(入栈需判断入栈索引小于入栈的次序大小)
	//出栈索引未超过边界循环上一步
	while (OutIndex < OutSize)
	{
		while (StackEmpty(&s) || TopStack(&s) != Out[OutIndex])
		{
			if (InIndex < InSize)		//入栈索引小于入栈数组的大小
				PushStack(&s, In[InIndex++]);
			else						//入栈次序的索引越界
				return 0;
		}
		//栈不为空,且栈顶和出栈次序的索引指向的元素相同
		PopStack(&s);
		OutIndex++;
	}
	return 1;
}

void TestStackValid()
{
	int tmp = 0;
	int In[] = { 1, 2, 3, 4, 5 };
	int Out[] = { 4, 5, 3, 1, 2 };
	TestStackInAndOutValid(In, 5, Out, 5);
	if (tmp)
	{
		printf("匹配成功!\n");
	}
	else
	{
		printf("匹配失败!\n");
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值