Skip to content

Instantly share code, notes, and snippets.

@jingz8804
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jingz8804/9450875 to your computer and use it in GitHub Desktop.
Save jingz8804/9450875 to your computer and use it in GitHub Desktop.
import java.util.Iterator;
import java.util.NoSuchElementException;
public class ResizingArrayStack<Item> implements Iterable<Item>{
private Item[] values;
private int count;
public ResizingArrayStack(){
values = (Item[]) new Object[1]; // initialize the array to hold 1 element
count = 0;
}
public int size(){
return count;
}
public void push(Item val){
if (count == values.length) resize(2 * values.length);
values[count++] = val; // be careful about the index. If you are not sure, draw a picture and see for yourself
}
public Item pop() throws Exception{
if (count == 0) throw new Exception("The Stack is already empty");
Item val = values[--count];
values[count] = null; // avoid loitering
if (count > 0 && count == values.length / 4) resize(values.length / 2); // shrink the array after pop
return val;
}
public void resize(int size){
Item[] newValues = (Item[]) new Object[size];
for (int i = 0 ; i < count; i++){
newValues[i] = values[i];
}
values = newValues;
}
public Iterator<Item> iterator(){
return new ReverseArrayIterator();
}
private class ReverseArrayIterator implements Iterator<Item>{
private int i = count;
public boolean hasNext() {i > 0;}
public void remove() {throw new UnsupportedOperationException();}
public Item next(){
if(!hasNext()) throw new NoSuchElementException();
Item item = values[--i];
return item;
}
}
}
@jingz8804
Copy link
Author

  • Check for loitering
  • Check for empty stack before halving

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment