剑指 Offer 31. 栈的压入、弹出序列

剑指 Offer 31. 栈的压入、弹出序列

题目描述

在这里插入图片描述

C++解法

/*输入两个整数序列,第一个序列表示亚茹顺序,判断第二个序列是否是他的输出序列*/
#include<iostream>
#include<stack>
#include<vector>
using namespace std;

//判断出栈是否正确
bool validateStackSequences(vector<int>& pushed, vector<int>& popped)
{
    //先判断输入情况
    if (pushed.size() == 0)
        return true;

    int size = pushed.size();
    int count = 0;

    stack<int>st;
    //入栈
    for (int i = 0;i < size;i++)
    {
        st.push(pushed[i]);
        while (!st.empty() && st.top() == popped[count])
        {
            st.pop();
            count++;
        }

    }
    if (st.empty())
        return true;
    else
        return false;

}
void print(bool result)
{
    if (result)
        cout << "是正确的出栈序列" << endl;
    else
        cout << "不是正确的出栈序列" << endl;
}
//测试案例
void test()
{
    cout << "test" << endl;
    int n;
    cout << "请输入入栈序列长度" << endl;
    cin >> n;
    vector<int>pushed(n);
    vector<int>poped(n);
    for (int i = 0;i < n;i++)
    {
        cin >> pushed[i];
    }
    for (int i = 0;i < n;i++)
    {
        cin >> poped[i];
    }
    bool result = validateStackSequences(pushed, poped);
    if (result)
        cout << "是正确的出栈序列"<<endl;
    else
        cout << "不是正确的出栈序列"<< endl;

}
void Test1()
{
    cout << "test1" << endl;
    const int nLength = 5;
    vector<int> push= { 1, 2, 3, 4, 5 };
    vector<int> pop = { 4, 5, 3, 2, 1 };
    print(validateStackSequences(push, pop));
}

void Test2()
{
    cout << "test2" << endl;
    const int nLength = 5;
    vector<int> push = { 1, 2, 3, 4, 5 };
    vector<int> pop = { 3, 5, 4, 2, 1 };
    print(validateStackSequences(push, pop));
}


void Test3()
{
    cout << "test3" << endl;
    const int nLength = 1;
    vector<int> push = { 1 };
    vector<int> pop = {  2 };
    print(validateStackSequences(push, pop));
}

void Test4()
{
    cout << "test4" << endl;
    const int nLength = 1;
    vector<int> push = { 1 };
    vector<int> pop = { 1 };
    print(validateStackSequences(push, pop));
}

// push和pop序列只有一个数字
void Test5()
{
    cout << "test4" << endl;
    const int nLength = 0;
    vector<int> push ;
    vector<int> pop ;
    print(validateStackSequences(push, pop));
}


int main()
{
    test();
    Test1();
    Test2();
    Test3();
    Test4();
    Test5();
    return 0;
}

结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值