帮助实现All Nearest Smaller Values算法

dat*_*ili 4 java algorithm

http://en.wikipedia.org/wiki/All_nearest_smaller_values.这是问题的网站,这是我的代码,但我实现它有些麻烦:

import java.util.*;
public class stack{

    public static void main(String[]args){

        int x[]=new int[]{  0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };

        Stack<Integer> st=new Stack<Integer>();

        for (int a:x){
            while (!st.empty() && st.pop()>=a){
                System.out.println( st.pop());
                if (st.empty()){
                    break;
                }
                else{
                    st.push(a);
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是网站的伪代码:

S = new empty stack data structure
for x in the input sequence:
    while S is nonempty and the top element of S is greater than or equal to x:
        pop S
    if S is empty:
        x has no preceding smaller value
    else:
        the nearest smaller value to x is the top element of S
    push x onto S
Run Code Online (Sandbox Code Playgroud)

我的代码有什么问题?

Ber*_*ron 5

该方法pop()不符合您的想法.你应该阅读Stack文档.