判斷出棧序列是否正確

題目:輸入兩個整數序列。其中一個序列表示棧的push順序,

判斷另一個序列有沒有可能是對應的pop順序

思路如下:pop的數字正好是棧頂數字,直接pop出棧即可;
如果希望pop的數字目前不在棧頂,我們就到

push序列中還沒有被push到棧裏的數字中去搜索這個數字,

並把在它之前的所有數字都push進棧。

如果所有的數字都被push進棧仍然沒有找到這個數字,表明該序列不可能是一個pop序列。

代碼如下:

#include<iostream>
#include<stack>
using namespace std;

stack<int> stackvolume;

bool PopOrder(int* Data,int *Poporder,int length)
{
	int i = 0;
	int datano = 0;
	while(i < length)
	{
		if(!stackvolume.empty() && stackvolume.top() == Poporder[i])
			stackvolume.pop();
		else
		{
			while((datano < length) && (Data[datano] != Poporder[i]))
				stackvolume.push(Data[datano++]);
			if((datano == length) && (Data[datano - 1] != Poporder[i]))
				return false;
		}
		i++;
	}
	return true;
}

int main()
{
	int Data[] = {1,2,3};
	int Poporder[] = {3,1,2};
	int length = 3;
	if(PopOrder(Data,Poporder,length))
		cout<<"The Order may be the Order of Pop"<<endl;
	else
		cout<<"The Order is not the Order of Pop"<<endl;
		return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章