Skip to content

Instantly share code, notes, and snippets.

@mbarinov
Created June 15, 2014 17:01
Show Gist options
  • Save mbarinov/730ee386a7597d2d73c9 to your computer and use it in GitHub Desktop.
Save mbarinov/730ee386a7597d2d73c9 to your computer and use it in GitHub Desktop.
import edu.princeton.cs.introcs.StdOut;
import java.util.Arrays;
import java.util.Iterator;
class ResizebleStack<Item> implements Iterable<Item> {
private Item[] stack = (Item[]) new Object[1];
private int N;
public Item pop() {
if (N > 0 && stack.length / 2 == N) {
stack = Arrays.copyOf(stack, N);
}
N--;
Item item = stack[N];
stack[N] = null;
return item;
}
public void push(Item item) {
if (stack.length == N) {
stack = Arrays.copyOf(stack, N * 2);
}
stack[N] = item;
N++;
}
public Iterator<Item> iterator() {
return new StackIterator();
}
private class StackIterator implements Iterator<Item> {
private int i = N;
public Item next() {
return stack[--i];
}
public boolean hasNext() {
return i > 0;
}
public void remove() {
}
}
}
class test {
public static void main(String[] args) {
ResizebleStack<Integer> stack = new ResizebleStack<Integer>();
stack.push(2);
stack.push(3);
stack.push(4);
for (Integer t : stack) {
StdOut.print(t);
}
stack.pop();
stack.pop();
for (Integer t : stack) {
StdOut.print(t);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment