Java一份stack的实现

如题:


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)");
		
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值