Last active
August 29, 2015 13:57
-
-
Save jingz8804/9450875 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
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; | |
} | |
} | |
} |
Author
jingz8804
commented
Mar 10, 2014
- 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