我必須檢查堆棧中的兩個值的和等於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