栈的压入弹出序列

题目描述:
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)

#include "stdafx.h"  
#include <iostream>  
#include <stack>  
using namespace std;  

bool IsPopOrder(int *pPush, int *pPop, int nLength)  
{  
   if (pPush == NULL || pPop == NULL || nLength <= 0)  
   {  
       return false;  
   }  

   stack<int> s;  
   s.push(pPush[0]);  
   int nPop_index = 0;  
   int nPush_index = 1;  
   while (nPop_index < nLength)  
   {  
       while (s.top() != pPop[nPop_index] && nPush_index < nLength)  
       {  
           s.push(pPush[nPush_index]);  
           nPush_index++;  
       }  

       if (s.top() == pPop[nPop_index])  
       {  
           s.pop();  
           nPop_index++;  
       }  
       else  
       {  
           return false;  
       }         
   }  

   return true;  
}  

int _tmain(int argc, _TCHAR* argv[])  
{  
    int nPush[5] = {1,2,3,4,5};   
    int nPop1[5] = {4,5,3,2,1};  
    int nPop2[5] = {4,3,5,1,2};  
    int nPop3[5] = {5,4,3,2,1};  
    int nPop4[5] = {4,5,2,3,1};  
    cout << IsPopOrder(nPush, nPop1, 5) << endl;  
    cout << IsPopOrder(nPush, nPop2, 5) << endl;  
    cout << IsPopOrder(nPush, nPop3, 5) << endl;  
    cout << IsPopOrder(nPush, nPop4, 5) << endl;  
    system("pause");  
    return 0;  
}  

另一个思路:

class Solution {
public:
    bool IsPopOrder(vector<int> pushV,vector<int> popV) {
        vector<int>temp;
         int j = 0;
        for(int i=0;i<pushV.size();)
         {
            temp.push_back(pushV[i++]);
            while(j<popV.size()&&temp[temp.size()-1]==popV[j])
            {
                temp.pop_back();
                ++j;
            }
         }
       return temp.empty();
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值