面试题20:栈的压入、弹出序列


思路:如果下一个弹出的数字刚好是栈顶数字,则直接弹出。若下一个弹出的数字不在栈顶,则把压栈序列中还没有入栈的数字压入辅助栈,直到把下一个需要弹出的数字压入栈顶为止。若所有的数字都压入栈了仍没有找到下一个弹出的数字,则表明该序列不可能滴一个弹出序列。

代码:

#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;
}


原文地址:https://www.cnblogs.com/dyllove98/p/3206463.html