notes100 - Stack, Queues, and Linked Lists Stack...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
Stack, Queues, and Linked Lists Stack Definition: A container of objects that are inserted and removed according to the Last In First Out (LIFO) principle. Basic operations: a. Push: Insert an item to the top of a stack b. Pop : Removes an item from the top of the stack and returns item Implementation of a Stack Using an Array: A stack of 5 elements Sample Code public class ArrayStack implements Stack { private int capacity; //max size private Object s[]; //stack array private int top; //top of stack public ArrayStack(int cap) { capacity = cap; s = new Object[cap]; top = -1; } public int size() { return top+1; } public boolean isEmpty() //true if stack is empty { return top==-1; } public void push(Object obj) throws StackFullException { if (size == capacity) throw new StackFullException(“Stack Full”); top++; s[top] = obj;
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
} public Object pop() Throws StackEmptyException { if(isEmpty()) throw new StackEmptyException(“Stack Empty”); Object tmp = s[top]; s[top]= null; top--; } } In this example, the array stack only stores element of type object. To store primitif type, use wrappers, type cast. To convert object to another element type, use type cast. Example code of storing integers in a stack ArrayStack s = new ArrayStack(10); s.push(new Integer(s)); Integer I = (Integer)s.pop(); int val=i.intValue();
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 02/02/2012 for the course CS 251 taught by Professor Staff during the Fall '08 term at Purdue University-West Lafayette.

Page1 / 6

notes100 - Stack, Queues, and Linked Lists Stack...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online