Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Iterator;
- import java.util.NoSuchElementException;
- public class Stack<E> implements Iterable<E>{
- private E[] arr;
- private int top = -1; // highest element id
- public Stack(int cap) {
- // Create array
- this.arr = (E[]) new Object[cap];
- }
- public E pop() {
- // If no elements yet - throw exception
- if (top < 0) {
- throw new NoSuchElementException();
- }
- E result = arr[top];
- arr[top] = null; // Allow garbage collector clearing
- top--; // decrease size
- // return element
- return result;
- }
- public void push(E e) {
- // If stack is full - throw exception
- if (top == arr.length) {
- throw new ArrayIndexOutOfBoundsException();
- }
- top += 1; // increase size
- arr[top] = e; // set element
- }
- public String toString() {
- if (top < 0) {
- return "[]";
- }
- StringBuilder sb = new StringBuilder();
- sb.append("[");
- for (int i = 0; i < top; i++) {
- sb.append(this.arr[i]).append(", ");
- }
- return sb.append(this.arr[top]).append("]").toString();
- }
- public static void main(String[] args) {
- Stack<String> stack = new Stack<>(11);
- stack.push("hello");
- stack.push("world");
- System.out.println(stack);
- stack.pop();
- System.out.println(stack);
- stack.pop();
- System.out.println(stack);
- Stack<Integer> intStack = new Stack<>(11);
- intStack.push(1);
- intStack.push(2);
- System.out.println(intStack);
- for (Integer i: intStack) {
- System.out.println(i);
- }
- intStack.pop();
- System.out.println(intStack);
- intStack.pop();
- System.out.println(intStack);
- for (Integer i: intStack) {
- System.out.println(i);
- }
- }
- @Override
- public Iterator<E> iterator() {
- return new StackIterator(this);
- }
- private class StackIterator implements Iterator<E> {
- private Stack<E> thisStack;
- private int position;
- private StackIterator(Stack<E> thisStack) {
- this.thisStack = thisStack;
- position = 0;
- }
- @Override
- public boolean hasNext() {
- return position <= thisStack.top;
- }
- @Override
- public E next() {
- position++;
- return thisStack.arr[position - 1];
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment