2012-04-16 56 views
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; 
} 

它編譯努力,但是沒有輸出,爲什麼呢?請幫我

+1

你all_smallest功能不會做任何事情,因爲它包含繼續線路將被永遠執行! – dexametason 2012-04-16 17:29:56

回答

1

檢查Wikipedia您沒有正確實施算法。下面是它應該是什麼:

#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 
+0

是的,我在想彈出和頂部應該在一起進行流行操作,所以我混合在一起,謝謝糾正 – 2012-04-16 17:51:33