• 栈的压入与弹出


    题目描述:输入两个序列,一个为压入的序列,一个为弹出的序列。检查这两个序列是否符合栈的压入和弹出的性质。

    算法实现:

     1 #include<iostream>
     2 #include<stack>
     3 using namespace std;
     4 
     5 bool IsPopOrder(const int *Push, const int *Pop, int nLength){
     6     bool tags = false;
     7     
     8     if(Push != NULL && Pop != NULL && nLength > 0){
     9         const int *tmpPush = Push;
    10         const int *tmpPop = Pop;
    11         
    12         stack<int> stackData;
    13         
    14         while(tmpPop - Pop < nLength){
    15             while(stackData.empty() || stackData.top() != *tmpPop){      //辅助栈非空,辅助栈的栈顶不等于下一个弹出的元素 
    16                 if(tmpPush - Push == nLength){
    17                     break;
    18                 }
    19                 
    20                 stackData.push(*tmpPush);       //压入辅助栈 
    21                 tmpPush++;
    22             }
    23             
    24             if(stackData.top() != *tmpPop){
    25                 break;
    26             }
    27             
    28             stackData.pop();          //弹出辅助栈的栈顶元素 
    29             tmpPop++;
    30         }
    31         
    32         if(stackData.empty() && tmpPop - Pop == nLength){
    33             tags = true;
    34         }
    35     }
    36     
    37     return tags;
    38 } 
    39 
    40 int main(){
    41     int pPush[] = {1, 2, 3, 4, 5};
    42     int pPop[] = {5, 4, 3, 2 ,1};
    43     int len = sizeof (pPush) / sizeof(int);
    44     bool result = IsPopOrder(pPush, pPop, len);
    45     if(result == true){
    46         cout<<"true order"<<endl;
    47     }
    48     else{
    49         cout<<"wrong order"<<endl;
    50     }
    51     return 0;
    52 }

      参考书籍:

    《剑指offer》

  • 相关阅读:
    flex 布局
    5个有用的 CSS 布局生成器
    js 函数
    js 类定义的方法(最终)
    js && ||
    css position 盒子模型
    eldatepicker选择时间,限定选择的时间段
    Java基础学习总结——Java对象的序列化和反序列化
    pytorch自定义算子
    网站上视频下载后保存为MP4格式
  • 原文地址:https://www.cnblogs.com/dormant/p/5374451.html
Copyright © 2020-2023  润新知