Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ///////////////////////////////////////////////////////////////////////////// IntrStack ADT (interface)
- public interface IntStack {
- /**
- * Puts the given element on the top of the stack.
- *
- * @param value element to be added on the top of the stack
- */
- public void push(int value);
- /**
- * Removes and returns the top most element of the stack
- *
- * @return the top most element of the stack
- * @throws Exception if the stack is empty
- */
- public int pop() throws Exception;
- /**
- * @return the size of the stack
- */
- public int getSize();
- /**
- * Removes all elements from the stack
- */
- public void clear();
- /**
- * @return a String representation of the stack
- */
- @Override
- public String toString();
- }
- ///////////////////////////////////////////////////////////////////////////////// ArrayIntStack Implementation
- public class ArrayIntStack implements IntStack{
- private int[] values;
- private int size;
- public ArrayIntStack(){
- values=new int[10];
- size=0;
- }
- @Override
- public void push(int value) {
- if (size==values.length){
- int[] tmpArr=new int[2*values.length];
- for (int i=0; i<values.length; i++)
- tmpArr[i]=values[i];
- values=tmpArr;
- }
- values[size++]=value;
- }
- @Override
- public int pop() throws Exception {
- if (size<=0){
- throw new Exception("The stack is empty.");
- }
- return values[(size--)-1];
- }
- @Override
- public int getSize() {
- return size;
- }
- @Override
- public void clear() {
- values=new int[10];
- size=0;
- }
- @Override
- public String toString(){
- String list="bottom[";
- for (int i=0; i<size; i++){
- list+=values[i];
- if (i<size-1)
- list+=", ";
- }
- return list+"]top";
- }
- }
- /////////////////////////////////////////////////////////////////////////////////// Test Classs
- public class testClass {
- public static void main(String[] args){
- IntStack myStack=new ArrayIntStack();
- try{
- System.out.println(myStack.pop()+"\n");
- } catch (Exception ex){
- System.out.println(ex.getMessage()+"\n");
- }
- for (int i=0; i<12; i++){
- myStack.push(i);
- }
- System.out.println(myStack);
- System.out.println("Size: "+myStack.getSize()+"\n");
- try {
- System.out.println("Elements removed: "+ myStack.pop()+" "+
- myStack.pop());
- } catch (Exception ex){
- System.out.println(ex.getMessage());
- }
- System.out.println(myStack);
- System.out.println("Size: "+myStack.getSize()+"\n");
- myStack.clear();
- System.out.println(myStack);
- System.out.println("Size: "+myStack.getSize()+"\n");
- for (int i=0; i<22; i++){
- myStack.push(i);
- }
- System.out.println(myStack);
- System.out.println("Size: "+myStack.getSize()+"\n");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment