Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package stackPractice;
- /**
- *
- * @author acer
- */
- public class ArrayStack implements Stack{
- int size;
- Object [] data;
- int top;
- public ArrayStack(){
- size=0;
- top=-1;
- data=new Object[7];
- }
- // The number of items on the stack
- public int size(){
- return top+1;
- }
- // Returns true if the stack is empty
- public boolean isEmpty(){
- if(top==-1){
- return true;
- }else{
- return false;
- }
- }
- // Pushes the new item on the stack, throwing the
- // StackOverflowException if the stack is at maximum capacity. It
- // does not throw an exception for an "unbounded" stack, which
- // dynamically adjusts capacity as needed.
- public void push(Object e) throws StackOverflowException{
- if(top+1==data.length){
- throw new StackOverflowException();
- }
- top++;
- data[top]=e;
- size++;
- }
- // Pops the item on the top of the stack, throwing the
- // StackUnderflowException if the stack is empty.
- public Object pop() throws StackUnderflowException{
- if(top==-1){
- throw new StackUnderflowException();
- }
- Object val=data[top];
- data[top]=null;
- top--;
- size--;
- return val;
- }
- // Peeks at the item on the top of the stack, throwing
- // StackUnderflowException if the stack is empty.
- public Object peek() throws StackUnderflowException{
- if(top==-1){
- throw new StackUnderflowException();
- }
- return data[top];
- }
- // Returns a textual representation of items on the stack, in the
- // format "[ x y z ]", where x and z are items on top and bottom
- // of the stack respectively.
- public String toString(){
- String str="[";
- for(int i=top;i>=0;i--){
- if(i==0){
- str+=data[i]+"]";
- }else{
- str+=data[i]+",";
- }
- }
- return str;
- }
- // Returns an array with items on the stack, with the item on top
- // of the stack in the first slot, and bottom in the last slot.
- public Object[] toArray(){
- Object [] arr=new Object[size()];
- int k=0;
- for(int i=top;i>=0;i--){
- arr[k]=data[i];
- k++;
- }
- return arr;
- }
- // Searches for the given item on the stack, returning the
- // offset from top of the stack if item is found, or -1 otherwise.
- public int search(Object e){
- int idx=-1;
- for(int i=0;i<size();i++){
- if(e.equals(data[i])){
- idx=i;
- }
- }
- return idx;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement