出棧的合法性檢測

對於一個給定的入棧順序,可能的出棧順序會有很多,但是肯定都要遵循棧“後進先出”的特點,那麼怎麼進行合法性檢測呢?

算法思想如下:

  1. 定義變量InIndex標記入棧序列的當前位置,定義OutIndex標記出棧序列的當前位置
  2. 對InIndex和Outindex處的數進行比較,如果相同,同時往後走。
  3. 如果不相同,則出棧序列去和輔助棧的棧頂的數據比較,如果相同,則pop掉棧頂,++OutIndex,然後繼續和棧頂比較,如果相同,只要入棧隊列沒走完,就將數據放入輔助棧。
  4. 如果入棧序列已經走完了,讓出棧序列依次棧頂數據比較,只要不匹配肯定是非法的。
    圖示如下:
    這裏寫圖片描述

基於這樣的思想,可以寫出如下代碼:

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

bool CheckStack(vector<int> In, vector<int> Out)
{
    if (In.size() != Out.size())//判斷入棧和出棧的個數是否相同
        cout << "Input Error!\n" << endl;

    stack<int> s;
    size_t InIndex = 0;
    size_t OutIndex = 0;
    while (InIndex <= In.size() && OutIndex <= Out.size())
    {
        if (In[InIndex] == Out[OutIndex])//如果入棧等於出棧,繼續往後比較
        {
            ++InIndex;
            ++OutIndex;
        }
        else if (!s.empty() && Out[OutIndex] == s.top())//如果入棧和出棧不匹配,出棧序列就去和棧頂比
        {
            while (!s.empty() && Out[OutIndex] == s.top())
            {
                s.pop();
                ++OutIndex;
            }
        }
        else//當前不匹配,入棧的序列繼續往後走
        {
            //將不匹配的先入到棧中
            s.push(In[InIndex]);
            ++InIndex;
        }

        if (InIndex >= In.size())//如果入棧序列已經走完,出棧序列和棧頂元素一一比較
        {
            while (!s.empty() && Out[OutIndex] == s.top())
            {
                s.pop();
                ++OutIndex;
            }

            //如果和棧中比較完,兩個序列都走完了,即表明順序合法
            if (InIndex == In.size() && OutIndex == Out.size())
            {
                return true;
            }

            //說明出棧的序列中和棧頂有不匹配的數,即出棧順序不合法
            else
            {
                return false;
            }
        }
    }
}

int main()
{
#if 0
    vector<int> In = { 1, 2, 3, 4, 5 };
    vector<int> Out = { 5, 4, 3, 2, 1 };
    cout<<CheckStack(In, Out)<<endl;
#endif

#if 1 
    vector<int> In = { 1, 2, 3, 4, 5 };
    vector<int> Out = { 3, 2, 1, 4, 5 };
    cout << CheckStack(In, Out) << endl;
#endif

#if 0
    vector<int> In = { 1, 2, 3, 4, 5 };
    vector<int> Out = { 5, 4, 2, 3, 1 };
    cout << CheckStack(In, Out) << endl;
#endif
    system("pause");
    return 0;
}

如有錯誤的地方,還望更正!

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