• 剑指Offer20 栈的压入弹出序列是否正确


     1 /*************************************************************************
     2     > File Name: 20_IsPopOrder.cpp
     3     > Author: Juntaran
     4     > Mail: JuntaranMail@gmail.com
     5     > Created Time: 2016年08月30日 星期二 19时53分19秒
     6  ************************************************************************/
     7 
     8 #include <stdio.h>
     9 #include <bits/stdc++.h>
    10 
    11 using namespace std;
    12 
    13 bool isPopOrder(int* push, int* pop, int length)
    14 {
    15     if (push==NULL || pop==NULL || length<=0)
    16         return false;
    17     
    18     int nextPush = 0;
    19     int nextPop  = 0;
    20     
    21     stack<int> stackData;
    22     while (nextPop < length)
    23     {
    24         // 如果当前栈为空 或栈顶元素不等于要出栈的元素,压栈
    25         while (stackData.empty() || stackData.top()!=pop[nextPop])
    26         {
    27             if (nextPush == length)
    28                 break;
    29             
    30             stackData.push(push[nextPush]);
    31             nextPush ++;
    32         }
    33         // 入栈队列结束还没找到钙元素, wrong
    34         if (stackData.top() != pop[nextPop])
    35             break;
    36         // 匹配到该元素,弹出,出栈指针后移一位
    37         stackData.pop();
    38         nextPop ++;
    39     }
    40     // 如果栈内已经没有元素且出栈指针已经走完,right
    41     if (stackData.empty() && nextPop==length)
    42         return true;
    43     
    44     return false;
    45 }
    46 
    47 int main()
    48 {
    49     int push[] = {1, 2, 3, 4, 5};
    50 //    int pop[]  = {4, 5, 3, 2, 1};
    51     int pop[]  = {4, 3, 5, 1, 2};
    52     int length = 5;
    53     if (isPopOrder(push, pop, length) == true)
    54         printf("Right
    ");
    55     else
    56         printf("Wrong
    ");
    57     
    58     return 0;
    59 }
  • 相关阅读:
    中文分词学习整理
    机器学习
    TimSort学习资料
    小段子
    Load和CPU利用率是如何算出来的
    sql server xml 截断
    System.Security.Cryptography.CryptographicException: 系统找不到指定的文件
    优化笔记: jxrsfxrxx_D_20140916.gz
    优化笔记: 此两个产品每天8点30分开始,要跑一个小时,看看是否有提升空间
    优化笔记:pfyhparopenfundinfotest_D_20140916.gz
  • 原文地址:https://www.cnblogs.com/Juntaran/p/5823515.html
Copyright © 2020-2023  润新知