Another method in the IntStack implementation should be the peak-method.
In the class IntStack: (Shown here
http://www.kandu.dk/dk/spg/60141)
you can add this method:
Kode private int[] structure;
private int count;
//supposed to let you see the element last added (by the put()-method
//without making any changes
public int peek() {
return structure[count-1];
} |
By having this method you can choose to "pop" if a certain number is the last.
Lets say you put the integers {3, 5, 7, 2} and for some reason you want only to hold odd numbers in your stack, but you want to be sure not to pop odd numbers:
Kode public static void main(String[] args) {
IntStack stack = new IntStack();
stack.put(3);
stack.put(5);
stack.put(7);
stack.put(2);
while(stack.peek()%2 != 0) {
stack.pop;
}
} |
After this test, there should only be the numbers {3, 5, 7} which is all odd numbers.
x%y produces the remainders of x divided by y. Any numbers for x divided by 2 will give 0 remainders if the number is even (like 2, 4, 6, 8...)
and the remainder will not be 0 (!=) if x is an odd number.
In this testcase we are lucky that only the last number is an even number. There are no operations (for the ADT of a Stack) to traverse the stack, but it is ofcourse possible by using another Stack.
In this example, the goal is to hold only odd numbers in stack1 at the end:
Kode public static void main(String[] args) {
IntStack stack1 = new IntStack();
IntStack stack2 = new IntStack();
for(int i = 1; i<= 10; i++) {
stack1.put(i);
}
//Now stack1 contains {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}.
//The first number to be popped is 10 because it was the last number added by "put()"
while(stack1.size() > 0) {
if(stack1.peek()%2 != 0) {
stack2.put(stack1.pop());
}
else {
stack1.pop();
}
}
//Now stack2 holds all the odd numbers, but in the wrong order.
//The first one to pop is 1. It should be 9, so I put them back:
while(stack2.size() > 0) {
stack1.put(stack2.pop());
}
} |
Now stack1 holds {1, 3, 5, 7, 9} and the fist one to pop is 9...
(at least I think... I didnt try, but you could try
)
In your test you could show by writing System.out.println(stack1);
By the way... change the toString()-method. Should be as follows:
Kode public String toString() {
StringBuffer buf = new StringBuffer();
int i = structure.length - 1;
buf.append("Index " + i + " = ");
for (i; i >= 1 ; i--) { //It´s a Stack so the list is supposed to be reversed....
buf.append(structure[i] + ", ");
}
buf.append(structure[i]) // to prevent a ", " as the last print....
return buf.toString();
} |