题目:输入两个整数序列,第一个序列表示栈的压入序列,请判断第二个序列是否为弹出序列。

思路:定义两个指针sPush和sPop分别指向两个整数序列的开头,借助一个辅助的栈,将第一个序列的数据依次压入栈中,直到压入栈中的数据和第二个栈中sPop所指向的数据相等,就将这个数据弹出栈。sPop指向下一个数字。重复上述过程。直到sPop等于序列的长度并且栈为空。

将抽象的问题具体化的过程如下:

C++代码:

#include<iostream>
#include<stack> bool isPopOrder(const int* sPush,const int* sPop,int nLength)
{
bool isPopOrder=false;
if(sPush!=NULL&&sPop!=NULL&&nLength>)
{
const int* pNextPush=sPush;
const int* pNextPop=sPop;
std::stack<int> stack;
while(pNextPop-sPop<nLength)
{
while(stack.empty()||*pNextPop!=stack.top())
{
if(pNextPush-sPush==nLength)
break;
stack.push(*pNextPush);
pNextPush++;
}
if(stack.top()!=*pNextPop)
break;
stack.pop();
pNextPop++; }
if(stack.empty()&&pNextPop-sPop==nLength)
isPopOrder=true;
}
return isPopOrder;
}
void test(const int* a,const int * b)
{
if(isPopOrder(a,b,))
printf("b是a的弹出序列\n");
else
printf("b不是a的弹出序列\n");
}
void main()
{
int a[]={,,,,};
int b[]={,,,,};
int c[]={,,,,};
test(a,b);
test(a,c); }

Java代码:

import java.util.Stack;
public class IsPopOrder {
public boolean isPopOrder(int[] sPush,int[] sPop,int length){
boolean isPop=false;
int sNextPush=;
int sNextPop=;
Stack<Integer> stack=new Stack<Integer>();
if(sPush!=null||sPop!=null||length>){
while(sNextPop<length){
while(stack.empty()||stack.peek()!=sPop[sNextPop])
{
if(sNextPush==length)
break;
stack.push(sPush[sNextPush]);
sNextPush++;
}
if((int)stack.peek()!=sPop[sNextPop])
break;
stack.pop();
sNextPop++;
}
if(stack.isEmpty()&&sNextPop==length){
isPop=true;
}
}
return isPop;
}
public static void main(String[] args)
{
int[] a={,,,,};
int[] b={,,,,};
int[] c={,,,,};
IsPopOrder ipo=new IsPopOrder();
if(ipo.isPopOrder(a, c, a.length))
System.out.print("true");
else
System.out.print("false");
}
}

最新文章

  1. Redis-基于php简单安装使用
  2. Webdriver实现原理
  3. Android 手机卫士--弹出对话框
  4. 利用PHP执行SQL文件,将SQL文件导入到数据库
  5. MillWheel: Fault-Tolerant Stream Processing at Internet Scale
  6. JS随鼠标坐标移动,显示浮动层内容
  7. 网络编程之PC版与Android手机版带断点续传的多线程下载
  8. jquery prop和attr的区别
  9. 在 ASP.NET Core 中使用 SignalR
  10. Android开发学习之路--NDK、JNI之初体验
  11. 我和Session的不解之“缘”(故事型技术长文)
  12. Python之列表方法
  13. jdbc问题:Access denied for user &#39;&#39;@&#39;localhost&#39;&#39;是因为没输入账户和密码
  14. HTML5⑥
  15. Cesium学习2:如何从零开始在Eclipse IDE,Java语言搭建cesium开发环境
  16. Node 系列之url模块
  17. Mongodb的下载和安装
  18. 安装 protoc 的各种坑
  19. go语言练习:go实现md5
  20. Http协议工作特点和工作原理笔记

热门文章

  1. Java开发资料汇编
  2. 20145219 《Java程序设计》实验四 Android开发基础设计实验报告
  3. 20145109 《Java程序设计》第七周学习总结
  4. 如何自定义echarts 线性图的选择事件
  5. 将CString写入到本地文件中
  6. QT的基本数据类型
  7. Recurrent Neural Networks vs LSTM
  8. 在Linux下创建分区和文件系统的方法详解
  9. linux下字典生成工具-crunch与rtgen
  10. windchill系统——开发_生命周期状态的增加