如题:
import java.util.Iterator;
import java.util.NoSuchElementException;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
public class StackAPI<Item> implements Iterable<Item> {
private Node<Item> first; //栈顶节点
private int n; //栈中元素个数
public StackAPI()
{
first=null;
n=0;
}
private static class Node<Item>//定义链表节点
{
private Item item;
private Node<Item> next;
}
public boolean isEmpty() {return first==null;}
public int size() {return n;}
public void push(Item item)
{
Node<Item> oldfirst=first;
first=new Node<Item>();
first.item=item;
first.next=oldfirst;
n++;
}
public Item pop()
{
if(isEmpty()) throw new NoSuchElementException("Stack underfloe");
Item item=first.item;
first=first.next;
n--;
return first.item;
}
public Item peek()
{
if(isEmpty()) throw new NoSuchElementException("Stack underfloe");
return first.item;
}
public String toString()
{
StringBuilder s=new StringBuilder();
for(Item item:this) //foreach 语句 ,需要接口迭代器
{
s.append(item);
s.append(' ');
}
return s.toString();
}
public Iterator<Item> iterator()
{
return new ListIterator<Item>(first);
}
private class ListIterator<Item> implements Iterator<Item>
{
private Node<Item> current;
public ListIterator(Node<Item> first)
{
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)
{
StackAPI<String> stack=new StackAPI<String>();
while(!StdIn.isEmpty())
{
String item=StdIn.readString();
if(!item.equals("-"))
stack.push(item);
else if(!stack.isEmpty())
StdOut.print(stack.pop()+" ");
}
StdOut.println("("+stack.size()+"left on stack)");
}
}