Object-Oriented Programming Simple Stack Implementation
Class Diagram (Stack of int) CIntStack -int mStack[]; -int mSize; -int mTop; CIntStack(int size); +boolean push(int item); +int pop(); +void resetStack(); +void stackInfo();
Variable Members int mStack[]; –Stack storage using array of integer int mSize; –Size of stack storage int mTop; –Stack pointer used to keep the stack position
Methods CIntStack(int size); –Constructor performs stack initialization –size is the size of stack storage boolean push(int item); –push() adds new item to the top of stack –mTop will be incremented if push() is successful –Method returns true if successful, false otherwise
Method (cont.) int pop(); –pop() retrieves the item from the top of stack –If stack is empty, pop() returns -1 void resetStack(); –Clear stack storage (by simply setting mTop to zero) void stackInfo(); –Print stack status
Class Attributes public class CIntStack { private int mStack[]; private int mSize; private int mTop; //all methods go here }
Constructor() public CIntStack(int size) { this.mStack = new int[size]; this.mSize = size; this.mTop = 0; System.out.println("Initialize Stack size to: " + this.mSize); }
push() public boolean push(int item) { if(this.mTop < this.mSize){ this.mStack[this.mTop++] = item; return true; } else return false; //Stack Overflow }
pop() public int pop() { if(this.mTop==0) // stack is empty, return -1 { System.out.println("ERR: Stack Underflow"); return -1; } else return this.mStack[--this.mTop]; // OK to pop }
stackInfo() public void stackInfo() { System.out.println(" "); System.out.println(“Size of Stack: “ + this.mSize); System.out.println(“Number of items: “ + this.mTop); System.out.println(" "); for(int i=0; i<this.mTop; i++) System.out.println(“: “ + this.mStack[i]); System.out.println(" "); }
resetStack() public void resetStack() { this.mTop = 0; }
Example of How to Use It public class myStack { public static void main(String[] args) { CIntStack st = new CIntStack(3); if(!st.push(1)) System.out.println("Overflow"); if(!st.push(2)) System.out.println("Overflow"); if(!st.push(3)) System.out.println("Overflow"); if(!st.push(4)) System.out.println("Overflow"); st.stackInfo(); System.out.println(st.pop()); //st.resetStack(); System.out.println(st.pop()); }