Java编写一个可迭代的Stack用例

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值