Skip to content

Instantly share code, notes, and snippets.

@wszdwp
Last active December 23, 2015 12:09
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 wszdwp/6633128 to your computer and use it in GitHub Desktop.
Save wszdwp/6633128 to your computer and use it in GitHub Desktop.
Coursera_Algorithm class practice: Generic stack using variable size array implementation
public class MyVarSizeArrayStack<Item>
{
private Item[] s;
private int index;
public MyVarSizeArrayStack() {
s = (Item[]) new Object[1];
index = 0;
}
public void resize(int capacity) {
Item[] copy = (Item[]) new Object[capacity];
for(int i = 0; i < index; i++) {
copy[i] = s[i];
}
s = copy;
}
public boolean isEmpty() {
return index == 0;
}
public void push(Item item) {
if( index == s.length ) resize( 2 * s.length);
s[index++] = item;
}
public Item pop() {
if( index == 0 ) return null;
if( index > 0 && index < s.length / 4) resize ( s.length / 2);
return s[--index];
}
public static void main(String[] args) {
MyArrayStack<Integer> s1 = new MyArrayStack<Integer>(5);
s1.push(1);
s1.push(2);
s1.push(3);
System.out.println(s1.pop());
System.out.println(s1.pop());
System.out.println(s1.pop());
System.out.println(s1.pop());
System.out.println(s1.isEmpty());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment