zoukankan      html  css  js  c++  java
  • 海涛老师的面试题作业22栈的压入、弹出序列

    题目:输入两个整数序列,第一个序列表示栈的压入顺序,判断第二个序列是否是该栈的弹出顺序,假设压入栈的所有数字均不相等,例如序列 1 2 3 4 5 是压栈顺序,而4 5 3 2 1是该压栈的序列对应的一个弹出序列,但是 4  3 5 1 2 不可能是该压栈序列的弹出序列

    View Code
     1 // 栈的压入弹出顺序.cpp : 定义控制台应用程序的入口点。
     2 //
     3 
     4 #include "stdafx.h"
     5 #include <stack>
     6 #include <iostream>
     7 using namespace std;
     8 
     9 
    10 bool IsPopOrder(const int* pPush,const int* pPop,int nLength)
    11 {
    12     bool bPossible=false;
    13 
    14     if(pPush&&pPop&&nLength>0)
    15     {
    16         const int* pNextPush=pPush;
    17         const int* pNextPop=pPop;
    18         stack<int>  stack;    
    19         while(pNextPop-pPop<nLength)
    20         {
    21             while(stack.empty()||stack.top()!=*pNextPop)
    22             {
    23                 if(pNextPush-pPush==nLength)
    24                     break;
    25                 stack.push(*pNextPush);
    26                 pNextPush++;
    27             }
    28             if(stack.top()!=*pNextPop)
    29                 break;
    30             stack.pop();
    31             pNextPop++;
    32         }
    33         if(stack.empty()&&pNextPop-pPop==nLength)
    34             bPossible=true;
    35     }
    36     return bPossible;
    37 }
    38 
    39 
    40 void Test1()
    41 {
    42     int arr[]={1,2,3,4,5};
    43     int brr[]={4,5,3,2,1};
    44     int crr[]={4,3,5,1,2};
    45     bool a_bOrder=IsPopOrder(arr,brr,5);
    46     bool a_cOrder=IsPopOrder(arr,crr,5);
    47     int temp=a_bOrder*2+a_cOrder;
    48     switch(temp)
    49     {
    50     case 0:
    51         cout<<"Both are Not sequence!"<<endl;
    52         break;
    53     case 1:
    54         cout<<"crr  are  The sequence!"<<endl;
    55         break;
    56     case 2:
    57         cout<<"brr  are  The sequence!"<<endl;
    58         break;
    59     case 3:
    60         cout<<"Both are sequence !"<<endl;
    61         break;
    62     default:
    63         break;
    64     }
    65 }
    66 
    67 
    68 int _tmain(int argc, _TCHAR* argv[])
    69 {
    70     Test1();
    71     return 0;
    72 }
  • 相关阅读:
    SQL语句集(转)
    Oracle 数据库 for update / for update nowait 的区别
    XML 关键字
    JAVA 操作 DBF 文件数据库
    Hibernate 懒加载和 Json 序列化冲突
    MYSQL 语法大全自己总结的
    php-laravel中间件使用
    php-表单验证
    php-laravel安装与使用
    iOS 关于权限设置的问题
  • 原文地址:https://www.cnblogs.com/cslave/p/2569998.html
Copyright © 2011-2022 走看看