0

我想构建我的代码来解决所有最近的较小值问题,这是我的努力

#include<iostream>
#include<stack>
using namespace std;
void all_smallest(int a[],int n)
{
    stack<int>s;
    for(int x=0;x<n;x++)
    {
        while(!s.empty() && s.top()>=a[x])
        {
            cout<<s.top();
            s.pop();
        }
        if(s.empty()){ continue;}
        else
        {
            s.push(a[x]);
        }

    }
}

int main()
{
    int a[]={0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15};
    int n=sizeof(a)/sizeof(a[0]);
    all_smallest(a,n);

    return 0;
}

它编译,但没有输出,为什么?请帮助我

4

2 回答 2

2

检查维基百科你没有正确实现算法。应该是这样的:

    #include<iostream>
    #include<stack>
    using namespace std;
    void all_smallest(int a[],int n)
    {
        stack<int>s;
        for(int x=0;x<n;x++)
        {
            while(!s.empty() && s.top()>=a[x])
            {
                s.pop();
            }
            if(!s.empty())
            {
                cout<<s.top();
            }
            s.push(a[x]);
        }
    }

    int main()
    {
        int a[]={0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15};
        int n=sizeof(a)/sizeof(a[0]);
        all_smallest(a,n);
        cout << "\n";
        return 0;
    }

输出:

    004022601151337
于 2012-04-16T17:41:55.900 回答
1

由于 s 一开始是空的,所以else子句永远不会发生(所以 s 保持为空)。

于 2012-04-16T17:29:33.383 回答