120 likes | 204 Views
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.
E N D
Object-Oriented Programming Simple Stack Implementation
Class Diagram (Stack of int) CIntStack -intmStack[]; -intmSize; -intmTop; 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(intsize); • 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 { privateintmStack[]; privateintmSize; privateintmTop; //all methods go here }
Constructor() publicCIntStack(intsize) { this.mStack = newint[size]; this.mSize = size; this.mTop = 0; System.out.println("Initialize Stack size to: " + this.mSize); }
push() publicbooleanpush(intitem) { if(this.mTop < this.mSize){ this.mStack[this.mTop++] = item; returntrue; } elsereturnfalse; //Stack Overflow }
pop() publicintpop() { if(this.mTop==0) // stack is empty, return -1 { System.out.println("ERR: Stack Underflow"); return -1; } elsereturnthis.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(inti=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()); System.out.println(st.pop()); //st.resetStack(); System.out.println(st.pop()); System.out.println(st.pop()); } }