Last active
December 23, 2015 12:09
-
-
Save wszdwp/6633128 to your computer and use it in GitHub Desktop.
Coursera_Algorithm class practice: Generic stack using variable size array implementation
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
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