zoukankan      html  css  js  c++  java
  • 栈和队列常考面试题(二)

    4.判断元素出栈,入栈顺序的合法性,如入栈序列是(1,2,3,4,5),出栈序列是(4,5,3,2,1)是合法序列
    入栈序列是(1,2,3,4,5),出栈序列是(1,5,3,2,4)

    思路:首先判断栈的长度,如果小于0则退出。根据给定的出栈序列,不断地进行入栈出栈操作,如果所有元素都能全部入栈并且出栈,则说明出栈序列是合法的。
    #include<iostream>
    using namespace std;
    #include<stack>

    bool IsPopOrder(const int* pPush, const int* pPop, int nLength)
    {
        if (nLength < 0)     //如果栈中的元素小于0
            return false;
        stack<int> s;
        int i=0, j=0;    //i是入栈,j是出栈
        while (j < nLength)
        {
            while (s.empty() || s.top() != pPop[j])
            {
                if (i == nLength)
                    break;
                s.push(pPush[i++]);
            }
            if (s.empty() || s.top() != pPop[j])
                break;
            s.pop();
            j++;
        }
        if (s.empty() && j == nLength)
            return true;
        return false;
    }

    //测试
    void main()
    {
        int pPush[5] = { 1, 2, 3, 4, 5 };
        //int pPop[5] = { 4, 5, 3, 2, 1 };
        int pPop[5] = {1,5,3,2,4 };
        cout << IsPopOrder(pPush, pPop, 5) << endl;
    }

    5.一个数组实现两个栈

    思路:数组两端即为两个栈的栈顶,在数组顶端的栈增加元素就是将栈顶指针++,然后将数据放进去,在数组尾部增加元素就是将栈顶指针--;然后放入数据。在数组顶端的栈出栈只需栈顶指针--,在数组尾部的栈出栈只需要栈顶指针++
    #include<iostream>
    #include<string>
    using namespace std;

    int A[9] = {0};
    int top_s1 = 0, top_s2 = 9;
    bool Push(string s,int x)
    {
        if (top_s2 - top_s1 == 1)
            return false;   //数组空间已经被占用完
        else
        {
            if (s == "s1")
            {
                top_s1++;
                A[top_s1] = x;
            }
            if (s == "s2")
            {
                top_s2--;
                A[top_s2] = x;
            }
        }
    }
    int Pop(string s)
    {
        if (s == "s1"&&top_s1 == 0 || s == "s2"&&top_s2 == 9)   //没有元素出栈的情况
            return -1;
            
        else
        {
            if (s == "s1")
            {
                --top_s1;
                return A[top_s1 + 1];
            }
            if (s == "s2")
            {
                ++top_s2;
                return A[top_s2 - 1];
            }
        }
    }

    //测试
    void main()
    {
        Push("s1", 12);
        Push("s1", 2);
        Push("s1", 9);

        Push("s2", 1);
        Push("s2", 33);
        
        cout << Pop("s1") <<"  ";
        cout << Pop("s1") << "  ";
        cout << Pop("s1") << "  ";
        cout << Pop("s1") << "  ";
        cout << endl;
        cout << Pop("s2") << "  ";
        cout << Pop("s2") << "  ";
        cout << endl;
    }

  • 相关阅读:
    【IDEA】颜色主题 Color Theme
    【IDEA】IntelliJ IDEA 2020.1破解版
    【HTML】基础
    SQLyog
    【GitHub】本地代码上传
    【NetWork】外网和内网
    C#根据PDF模板生成内容
    layui数据表格显示与导出问题
    LayUIDataResult
    LayUIParameter
  • 原文地址:https://www.cnblogs.com/qingjiaowoxiaoxioashou/p/5878775.html
Copyright © 2011-2022 走看看