What is Stack
Code Example of Stack
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Scanner;
class Stack<Item> implements Iterable<Item> {
private int n;
private Node first;
private class Node {
private Item item;
private Node next;
}
public Stack() {
first = null;
n = 0;
}
public boolean isEmpty() {
return first == null;
}
public void push(Item item) {
Node oldFirst = first;
first = new Node();
first.item = item;
first.next = oldFirst;
n++;
}
public Item pop() {
if (isEmpty()) throw new NoSuchElementException("Stack underflow");
Item item = first.item;
first = first.next;
n--;
return item;
}
public int size() {
return n;
}
public String toString() {
StringBuilder str = new StringBuilder();
for (Item item : this) {
str.append(item);
str.append(' ');
}
return str.toString();
}
public Iterator<Item> iterator() {
return new ListIterator();
}
private class ListIterator implements Iterator<Item> {
private Node current = first;
public boolean hasNext() {
return current != null;
}
public void remove() {
throw new UnsupportedOperationException();
}
public Item next() {
if (!hasNext()) throw new NoSuchElementException();
Item item = current.item;
current = current.next;
return item;
}
}
public static void main(String[] args) {
Stack<String> stack = new Stack<String>();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String item = scanner.next();
if (!item.equals("-")) {
stack.push(item);
} else if (!stack.isEmpty()) {
System.out.println(stack.pop() + " ");
}
}
System.out.println(stack.toString());
System.out.println("(" + stack.size() + " left on stack)");
}
}