Last active
August 29, 2015 14:00
-
-
Save skharel/11119063 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* | |
* This code is written for Stacks tutorial | |
* The comment won't make sense unless you read the slide that goes with it | |
* | |
* Go to Vumari.com to find the slide | |
* | |
*/ | |
import java.util.Arrays; | |
public class ArrayBasedStacks { | |
private Integer stacks[]; | |
private int index = 0; | |
public ArrayBasedStacks(int size){ | |
stacks = new Integer[size]; | |
} | |
public void push(int data){ | |
if(index == stacks.length){ | |
//you can either resize here or throw exception | |
throw new ArrayIndexOutOfBoundsException("Stack is already full"); | |
} | |
//add item to current index & increase index by 1; | |
stacks[index++] = data; | |
} | |
public int pop(){ | |
if(isEmpty()){ | |
throw new NullPointerException("There is nothing to pop from the stack."); | |
} | |
int temp = stacks[--index]; | |
stacks[index] = null; | |
return temp; | |
} | |
public int getSize(){ | |
//index is 0 based but our index always points to next empty location | |
//that will compensate for 0 & return exact size | |
return index; | |
} | |
public boolean isEmpty(){ | |
return index == 0; | |
} | |
@Override | |
public String toString() { | |
StringBuilder stackData = new StringBuilder(Arrays.deepToString(stacks)); | |
return stackData.reverse().toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment