import java.util.Iterator;
public class Stack<T> implements Iterable<T> {
private T[] stack = (T[]) new Object[1];
private int N = 0;
public boolean isEmpty(){
return N == 0;
}
public int size() {
return N;
}
private void resize(int max) {
T[] temp = (T[]) new Object[max];
for(int i=0;i<N;i++) {
temp[i] = stack[i];
}
stack = temp;
}
public void push(T item) {
if(N== stack.length)
resize(2* stack.length);
stack[N++] = item;
}
public T pop () {
T temp = stack[--N];
stack[N] = null;
if(N>0 && N == stack.length/4) resize(stack.length/2);
return temp;
}
public Iterator<T> iterator() {
return new ReverseIterator();
}
private class ReverseIterator implements Iterator<T> {
private int i =N;
public boolean hasNext() {
return i > 0;
}
public T next() {
return stack[--i];
}
public void remove() {
}
}
}
import java.util.Iterator;
public class liststack<T> implements Iterable<T>{
private int N;
private Node first;
private class Node {
private T item;
private Node next;
}
public Stack() {
first = null;
N = 0;
}
boolean isEmpty() {
return first == null;
}
public int size() {
return N;
}
public void push(T item) {
Node old_first = first;
first = new Node();
first.item = item;
first.next = old_first;
N++;
}
public T pop() {
T temp = first.item;
first = first.next;
N -- ;
return temp;
}
public Iterator<T> iterator() {
return new ListIterator();
}
public class ListIterator implements Iterator<T> {
private Node current = first;
public boolean hasNext() {
return current != null;
}
public T next() {
T item = current.item;
current = current.next;
return item;
}
}
}