http://en.wikipedia.org/wiki/All_nearest_smaller_values. This is the site of the problem
and here is my code, but I have some trouble to implement it:
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);
}
}
}
}
}
And here is the pseudo code from the site:
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
What is the matter with my code?
Here is the same pseudo code but I’ve added brackets so you can see where each statement begins and ends.
You had the if/else statement inside the while loop, which was incorrect.
Check the documentation of the stack to understand what
push,popandpeekdo, here is the documentation: http://java.sun.com/j2se/1.4.2/docs/api/java/util/Stack.html