您的位置:首页 > 其它

九度 OJ 题目1366:栈的压入、弹出序列

2014-07-28 13:58 309 查看
题目描述:
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列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


1.

#include <stdio.h>
#include <stdlib.h>

int isPopOrder(const int *pPush, const int *pPop, int n)
{
	const int *pNextPush = pPush;
	const int *pNextPop  = pPop;
	int top = -1;   /*空栈*/
	int *st = NULL; /*模拟栈*/

	/*边界测试*/
	if (pPush==NULL || pPop==NULL || n<=0)
	{
		return 0;
	}

	st = (int *)malloc(sizeof(int)*n);
	while ((pNextPush - pPush) < n)
	{
		st[++top] = *pNextPush;
		++pNextPush;

		while (top>=0 && st[top]==*pNextPop)
		{
			++pNextPop;
			--top;
		}
	}

	free(st);
	st = NULL;

	return (top != -1) ? 0 : 1; /*栈是否为空*/
}

int main(void)
{
	int n;

	while (scanf("%d", &n) != EOF)
	{
		int i;
		int *pPush = (int *)malloc(sizeof(int)*n);
		int *pPop  = (int *)malloc(sizeof(int)*n);

		for (i=0; i<n; ++i)
		{
			scanf("%d", &pPush[i]);
		}

		for (i=0; i<n; ++i)
		{
			scanf("%d", &pPop[i]);
		}

		if (isPopOrder(pPush, pPop, n))
		{
			printf("Yes\n");
		}
		else
		{
		printf("No\n");
		}

		free(pPush);
		free(pPop);
		pPush = NULL;
		pPop = NULL;
	}

	return 0;	
}



2.STL stack容器

#include <stack>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

bool isPopOrder(const int *pPush, const int *pPop, int n)
{
	const int *pNextPush = pPush;
	const int *pNextPop  = pPop;
	stack<int> st;

	/*边界测试*/
	if (pPush==NULL || pPop==NULL || n<=0)
	{
		return false;
	}

	/*压栈序列尚未全部进栈*/
	while ((pNextPush - pPush) < n)
	{	
		st.push(*pNextPush);
		++pNextPush;

		/*辅助栈不为空且栈顶元素==弹出序列的当前元素,辅助栈元素出栈*/
		while (!st.empty() && st.top()==*pNextPop)
		{
			st.pop();
			++pNextPop;
		}
	}

	return st.empty(); /*辅助栈是否为空*/
}

int main(void)
{
	int n;

	while (scanf("%d", &n) != EOF)
	{
		int i;
		int *pPush = (int *)malloc(sizeof(int)*n);
		int *pPop  = (int *)malloc(sizeof(int)*n);

		for (i=0; i<n; ++i)
		{
			scanf("%d", &pPush[i]);
		}

		for (i=0; i<n; ++i)
		{
			scanf("%d", &pPop[i]);
		}

		if (isPopOrder(pPush, pPop, n))
		{
			printf("Yes\n");
		}
		else
		{
		printf("No\n");
		}

		free(pPush);
		free(pPop);
		pPush = NULL;
		pPop = NULL;
	}

	return 0;	
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: