



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
Stacks, LIFO ,functional requirements of stack , examples
Typology: Study notes
1 / 6
This page cannot be seen from the preview
Don't miss anything!
Notice that clients of the SimpleStack class only have access to the stack through the public methods isEmpty(), isFull(), push() and pop(). The actual stack array and the pointer top are private and cannot be directly manipulated by the client. Arrays are not the only way to implement a stack – we can also use linked lists (later in the course). the Java construct of the interface:
Now we shall see how we can use the stack interface to create a new stack class StackArray. StackArray will be able to deal with the situation when a stack needs to be re-sized because it is full. This will make use of a System Java method to copy one stack to another new one.
import java.util.NoSuchElementException; public class StackArray implements Stack { private Object[] stack; private int top; public StackArray() { stack = new Object[1]; top = 0; } public boolean isEmpty() { return (top==0); } public void push(Object item) { if (top==stack.length) { // expand the stack Object[] newStack = new Object[2*stack.length]; System.arraycopy(stack,0,newStack,0,stack.length); stack = newStack; } stack[top++] = item; } public Object pop() { if (top==0) { throw new NoSuchElementException(); } else { return stack[--top]; } } }
Now we can see StackArray in use:. Can’t instantiate Stack directly, as it’s only an interface. Need to “object”-ify items to put them on the stack.