2012-04-16 3 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

답변

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

예, 저는 pop과 top이 함께 pop operation을 수행해야한다고 생각 했었습니다. 그래서 나는 서로를 섞어서 고마워했습니다. –

1

를 도와주세요 s가 공백으로 시작하기 때문에 else 절이 발생하지 않습니다 (따라서 s는 비어있게됩니다).

관련 문제