Created
June 15, 2014 17:01
-
-
Save mbarinov/730ee386a7597d2d73c9 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 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