/** * ====================* Memory Calculations* ====================** Class Overhead + Inner class over head + Item + Node * * 16 + 8 + 8 + 8 = 40 bytes* * For N Nodes , Total Memory 40 * N ( in bytes )*/publicclassNode {String item;Node next;}
Using Array - Fixed size
publicclassArrayFixedSizeStack {int MAX_CAPACITY =0;// Top element in the stackprivateint N =0;publicArrayStack(int capacity){this.MAX_CAPACITY= capacity; }privateString[] stack =newString[MAX_CAPACITY];// check if stack is empty or notpublicbooleanisEmpty() {return N ==0; }// adding an element to the stackpublicvoidpush(String item) {if( N++<= MAX_CAPACITY){ stack[N++] = item; }else{thrownewStackOverflowException("Stack Over flow exception"); } }// deleting an element to the stackpublicStringpop(){if(N ==0 ){thrownewStackUnderflowException("Stack Underflow exception occured"); } return stack[--N]; }}
Using Array - dynamic size
publicclassArrayDynamicSizeStack {privateString[] stack;privateint N;// Initializing the size of the stack to '1'publicArrayDynamicSizeStack(){ stack =newString[1]; } // check if stack is empty or notpublicbooleanisEmpty() {returnstack.length==0; }// adding an element to the stackpublicvoidpush(String item) {if(N ==stack.length){resize(2*stack.length); } stack[N++] = item; }// deleting an element to the stackpublicStringpop(){String item = stack[--N]; s[N] =null;if (N >0&& N ==s.length/4){resize(s.length/2); }return item; }// resizing the capacity of the arraypublicvoidreSize(int capacity){String copy =newString[capacity];for(int i=0;i<N;i++){ copy[i] = stack[i]; } stack = copy; }}
Generic Stack Linked List Implementation
publicclassStack<K> {privateNode first =null;privateclassNode {K item;Node next; }publicbooleanisEmpty() {return first ==null; }publicvoidpush(K item) {Node oldfirst = first; first =newNode();first.item= item;first.next= oldfirst; }publicKpop() {K item =first.item; first =first.next;return item; }}
Generic Stack Array Implementation
publicclassFixedCapacityStack<K> {privateK[] s;privateint N =0;publicFixedCapacityStack(int capacity) { s = (K[]) newObject[capacity]; }publicbooleanisEmpty() {return N ==0; }publicvoidpush(K item) { s[N++] = item; }publicKpop() {return s[--N]; }}
Stack Iteration
publicclassstackIteration {....for (String s : stack) System.out.println(s);...}
Trade offs
Can implement a stack with either resizing array or linked list. Which one is better?
Linked List Implementation:
Every operation takes constant time in the worst case.