【剑指offer】堆栈推弹出序列

转载请注明出处:http://blog.csdn.net/ns_code/article/details/26077863


    剑指offer上的第22题,九度OJ上AC。

题目描写叙述:

输入两个整数序列。第一个序列表示栈的压入顺序,请推断第二个序列是否为该栈的弹出顺序。假设压入栈的全部数字均不相等。

比如序列1,2,3,4,5是某栈的压入顺序,序列4。5,3,2,1是该压栈序列相应的一个弹出序列。但4,3,5,1,2就不可能是该压栈序列的弹出序列。

输入:

每一个測试案例包括3行:

第一行为1个整数n(1<=n<=100000),表示序列的长度。

第二行包括n个整数。表示栈的压入顺序。

第三行包括n个整数,表示栈的弹出顺序。

输出:

相应每一个測试案例,假设第二个序列是第一个序列的弹出序列输出Yes。否则输出No。

例子输入:
5
1 2 3 4 5
4 5 3 2 1
5
1 2 3 4 5
4 3 5 1 2
例子输出:
Yes
No

    判定方法例如以下:

    假设第二个序列中当前要推断的元素刚好与栈顶元素相等,则直接pop出来,假设不等,则将第一个序列的后面还没有入栈的元素入栈,直到将与之相等的元素入栈为止,假设第一个序列的全部的元素都入栈了。还没有找到与之相等的元素,则说明第二个序列不是第一个序列的弹出序列,

    AC代码例如以下:

/*
本程序採用数组模拟栈
*/
typedef int ElemType;
#define MAX 100000 //栈的深度
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>

int top = -1;
/*
在栈顶索引指针为top时。向栈A中压入数据data
*/
bool push(int *A,ElemType data)
{
	if(top>=MAX-1 || top<-1)
		return false;

	A[++top] = data;
	return true;
}

/*
在栈顶索引指针为top时,出栈
*/
bool pop()
{
	if(top<0)
		return false;

	top--;
	return true;
}

/*
推断popList是否是pushList的弹出序列
*/
bool IsPopOrder(int *pushList,int *popList,int len,int *stack)
{
	if(popList==NULL || pushList==NULL || len<1)
		return false;

	int i;
	int pushIndex = 0;
	for(i=0;i<len;i++)
	{
		while(top==-1 || stack[top] != popList[i])
		{
			//假设没有元素能够push了,就说明不符合
			if(pushIndex == len)
				return false;
			push(stack,pushList[pushIndex++]);
		}
		pop();
	}
	return true;
}

int main()
{
	int n;
	int stack[MAX]; //辅助栈
	while(scanf("%d",&n) != EOF)
	{
		int *pushList = (int *)malloc(n*sizeof(int));
		if(pushList == NULL)
			exit(EXIT_FAILURE);
		int i;
		for(i=0;i<n;i++)
			scanf("%d",pushList+i);

		int *popList = (int *)malloc(n*sizeof(int));
		if(popList == NULL)
			exit(EXIT_FAILURE);
		for(i=0;i<n;i++)
			scanf("%d",popList+i);

		if(IsPopOrder(pushList,popList,n,stack))
			printf("Yes
");
		else
			printf("No
");

		free(pushList);
		pushList = NULL;
		free(popList);
		popList = NULL;
	}
	return 0;
}

/**************************************************************
    Problem: 1366
    User: mmc_maodun
    Language: C
    Result: Accepted
    Time:210 ms
    Memory:2012 kb
****************************************************************/


版权声明:本文博主原创文章。博客,未经同意不得转载。

原文地址:https://www.cnblogs.com/zfyouxi/p/4800641.html