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);
}
}
}
}
}
以下是该网站的伪代码:
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
我的代码有什么问题?
答案 0 :(得分:5)
方法pop()
没有按照您的想法执行。您应该阅读Stack
documentation。
答案 1 :(得分:1)
这是相同的伪代码,但我添加了括号,以便您可以看到每个语句的开始和结束位置。
S = new empty stack data structure
for x in the input sequence:
{
// peek instead of pop when you're checking what's in the queue
while S is nonempty and the top element of S is greater than or equal to x:
{
pop S // you can call pop here
}
if S is empty: // just check if the queue is empty, don't peek or pop
{
x has no preceding smaller value
}
else:
{
the nearest smaller value to x is the top element of S
}
push x onto S
}
你在while循环中有if / else语句,这是不正确的。
查看堆栈文档以了解push
,pop
和peek
的作用,以下是文档:http://java.sun.com/j2se/1.4.2/docs/api/java/util/Stack.html
答案 2 :(得分:1)
在发布的伪代码中,while
与if
/ else
分开;在您的Java代码中,if
位于while
。
同样pop()
删除堆栈的顶部元素。您无法使用它来查看while
条件下的第一个元素。
答案 3 :(得分:0)
这样的事情会起作用吗?
int[] inputSequence = new int[] { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5,
13, 3, 11, 7, 15 };
Stack<Integer> S = new Stack<Integer>(); // empty stack data structure
for (int x : inputSequence) {
while (!S.isEmpty() && topElementOf(S) >= x) {
S.pop();
}
if (S.isEmpty())
System.out.println(x + " has no preceding smaller value");
else {
System.out.println("the nearest smaller value to " + x + " is "
+ topElementOf(S));
}
S.push(x);
}
private Integer topElementOf(Stack<Integer> stack) {
return stack.peek();
}