Java编写一个可迭代的Stack用例,它含有一个静态的copy()方法,接受一个字符串的栈作为参数并返回该栈的副本。
主要就是在Stack中添加一个copy方法,下面是编写的Stack100312类的具体实现:
import java.util.Iterator;
public class Stack100312<Item> implements Iterable<Item>
{
private Node first;//栈顶元素
private int N;
public boolean isEmpty()
{
return first==null;
}
public int size()
{
return N;
}
public void push(Item item)
{
Node oldfirst=first;
first=new Node();
first.item=item;
first.next=oldfirst;
N++;
}
public Item pop()
{
Item item=first.item;
first=first.next;
N--;
return item;
}
public static <Item> Stack100312<Item> copy(Stack100312<Item> s)
{
Iterator<Item> it=s.iterator();
Stack100312<Item> result=new Stack100312<Item>();
Stack100312<Item> temp=new Stack100312<Item>();
while(it.hasNext())
{
temp.push(it.next());
}
it=temp.iterator();
while(it.hasNext())
{
result.push(it.next());
}
return result;
}
private class Node
{
Item item;
Node next;
}
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() {}
public Item next()
{
Item item=current.item;
current=current.next;
return item;
}
}
}
测试代码:
public class Q100312 {
public static void main(String[] args)
{
Stack100312<String> s1=new Stack100312<String>();
s1.push("1");
s1.push("2");
s1.push("3");
Stack100312<String> s2=Stack100312.copy(s1);
while(!s2.isEmpty())
{
System.out.println(s2.pop());
}
}
}
输出:
3
2
1