现在的位置: 首页 > 综合 > 正文

29 栈的 push、pop 序列

2018年01月20日 ⁄ 综合 ⁄ 共 921字 ⁄ 字号 评论关闭
/*
29.栈的 push、pop  序列
题目:输入两个整数序列。其中一个序列表示栈的 push  顺序, 
61
判断另一个序列有没有可能是对应的 pop  顺序。
为了简单起见,我们假设 push  序列的任意两个整数都是不相等的。
比如输入的 push  序列是 1、2、3、4、5,那么 4、5、3、2、1  就有可能是一个 pop  系列。
因为可以有如下的 push  和 pop  序列:
push 1,push 2,push 3,push 4,pop,push 5,pop,pop,pop,pop,
这样得到的 pop  序列就是 4、5、3、2、1。
但序列 4、3、5、1、2  就不可能是 push  序列 1、2、3、4、5  的 pop  序列。

相同就出栈 ,否则进栈 
*/ 
#include<iostream>
#include<stack>
#include<stdio.h>
using namespace std;

int isPop(int push[],int pop[],int n)
{
	stack<int> ss;
	int i1=0,i2=0;
	while(i2<n)
	{
		if(ss.empty()||ss.top()!=pop[i2])
		{
			if(i1<n)
			{
				printf("Push:%d\n",push[i1]);
				ss.push(push[i1++]);
				
			}
			else 
				return 0;
		}
		while(!ss.empty()&&ss.top()==pop[i2])
		{
			
			printf("POP:%d\n",ss.top());
			ss.pop();
			i2++;
		}
	}
	return 1;
}

int main()
{
	int push1[5]={1,2,3,4,5};
	int pop1[5]={4,5,3,2,1};
	int pop2[5]={1,2,4,3,5};
	int pop3[5]={1,4,5,2,3};
	
	if(isPop(push1,pop1,5)==1)
		printf("YES\n");
	else
		printf("No\n");
		
	if(isPop(push1,pop2,5)==1)
		printf("YES\n");
	else
		printf("No\n");
		
	if(isPop(push1,pop3,5)==1)
		printf("YES\n");
	else
		printf("No\n");
	
	return 0;
} 

抱歉!评论已关闭.