为您的Stack实施提供更好的解决方案
import java.util.List;import java.util.ArrayList;public class IntegerStack{ private List<Integer> stack; public IntegerStack(int SIZE) { stack = new ArrayList<Integer>(SIZE); } public void push(int i) { stack.add(0,i); } public int pop() { if(!stack.isEmpty()){int i= stack.get(0);stack.remove(0);return i; } else{return -1;// Or any invalid value } } public int peek() { if(!stack.isEmpty()){return stack.get(0); } else{return -1;// Or any invalid value } } public boolean isEmpty() { stack.isEmpty(); } }如果您必须使用Array …这是您的代码中的问题以及可能的解决方案
import java.util.Arrays;public class IntegerStack { private int stack []; private int top; public IntegerStack(int SIZE) { stack = new int [SIZE]; top = -1; // top should be 0. If you keep it as -1, problems will arise when SIZE is passed as 0. // In your push method -1==0 will be false and your pre will try to add the invalid element to Stack .. }public void push(int i) { if (top == stack.length) { extendStack(); } stack[top]= i; top++;}public int pop() { top --; // here you are reducing the top before giving the Object back return stack[top];}public int peek(){ return stack[top]; // Problem when stack is empty or size is 0 }public boolean isEmpty() { if ( top == -1); // problem... we changed top to 0 above so here it need to check if its 0 and there should be no semicolon after the if statement { return true; }}private void extendStack(){ int [] copy = Arrays.copyOf(stack, stack.length); // The second parameter in Arrays.copyOf has no changes, so there will be no change in array length. } }


