我必须检查堆栈中的两个值的和等于100,并打印出indecis和数字。我已经使用数组实现了这种可能性,但是我无法使用堆栈使其工作。请帮帮我。直到现在我写下了以下内容,但没有给出正确的结果。Java - 堆栈 - 检查堆栈的两个数字是否相等100
import java.util.Stack;
public class 2 {
public static void main(String[] args) {
int x = 100;
Stack stack=new Stack();
Stack tempStack=new Stack();
stack.push(new Integer(20));
stack.push(new Integer(53));
stack.push(new Integer(41));
stack.push(new Integer(38));
stack.push(new Integer(28));
stack.push(new Integer(47));
stack.push(new Integer(70));
stack.push(new Integer(30));
stack.push(new Integer(80));
stack.push(new Integer(400));
stack.push(new Integer(3));
stack.push(new Integer(20));
tempStack = (Stack) stack.clone();
for (int i=0; i<stack.size(); i++) {
tempStack = (Stack) stack.clone();
int value = (Integer) stack.pop();
if (!stack.isEmpty()) {
for (int k=0; k<tempStack.size(); k++) {
int tmp = (Integer) tempStack.pop();
if ((value + tmp) == x) {
System.out.println("Indices " + i + " & " + k + " with values "
+ value + " & " + tmp);
}
}
}
}
}
}
以下是我的基于阵列的解决方案:
public class 1 {
public static void main(String[] args) {
int x = 100;
int [] array = {20,3,400,80,30,70,20,47,28,38,41,53,20};
for (int i=0; i<array.length; i++){
int temp1 = array[i];
for (int k=1; k<array.length; k++) {
int temp2 = array[k];
if ((temp1+temp2)==x)
System.out.println("Indices " + i + " & " + k + " with values "
+ temp1 + " & " + temp2);
}
}
}
}
基本堆栈用于编程语言的语法检查(在编译器中)和一些服务策略实现,如LIFO。在你的情况堆栈不是最好的数据结构。 – 2012-02-27 06:27:12