Download presentation
Presentation is loading. Please wait.
Published byAntonia Magdalen McKinney Modified over 9 years ago
1
Object-Oriented Programming Simple Stack Implementation
2
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();
3
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
4
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
5
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
6
Class Attributes public class CIntStack { private int mStack[]; private int mSize; private int mTop; //all methods go here }
7
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); }
8
push() public boolean push(int item) { if(this.mTop < this.mSize){ this.mStack[this.mTop++] = item; return true; } else return false; //Stack Overflow }
9
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 }
10
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("-------------------------"); }
11
resetStack() public void resetStack() { this.mTop = 0; }
12
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()); }
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.