---
title: "java实现Iterable接口的栈（stack）"
author: "akingde"
date: "2014-03-23T16:32:38Z"
tags: []
categories: ["编程语言"]
slug: "java-iterable-stack"
draft: false
lastmod: "2014-03-23T16:35:10Z"
id: 2035098
url: "https://akingde.iteye.com/blog/2035098"
---

```
//实现Iterable接口，实现迭代遍历
   public class Stack<Item> implements Iterable<Item>{
private Node first;
private int N;
//定义内部类作为栈中的每一个节点
private class Node{
    Item item;
    Node next;
}
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;
}
//实现迭代遍历时返回的Iterator
private class AIterator implements Iterator<Item>{
    private Node current=first;
    public boolean hasNext(){return current!=null;}
    public Item next(){
        Item item=current.item;
        current=current.next;
        return item;
    }
    @Override
    public void remove() {
    }
}
@Override
public Iterator<Item> iterator() {
    return new AIterator();
}
```