集册 Java实例教程 创建通用包数据结构

创建通用包数据结构

欢马劈雪     最近更新时间:2020-01-02 10:19:05

566
创建通用包数据结构

import static java.lang.System.out;

import java.util.Iterator;// 来 自 nowjava - 时  代  Java

import java.util.NoSuchElementException;



public class Bag<Item> implements Iterable<Item> {


    private int N;

    private Node first;

    

    private class Node {

        private Item item;

        private Node next;

    }
    /** from 
    N o w J a v a . c o m - 时  代  Java**/

    

    public void add(Item item) {

        Node oldfirst = first;

        first = new Node();

        first.item = item;

        first.next = oldfirst;

        N++;

    }

    

    public int size() {

        return N;

    }

    

    public boolean isEmpty() {

      return first == null;

    }

  

    /**

     * Implements a iterator for Stack, using LIFO.

     * 

     * <h5>Lecture: Iterators (Week 2)</h5>

     */

    private class ListIterator implements Iterator<Item> {

        private Node current = first;

        

        @Override

        public boolean hasNext() {

            return current != null;

        }

        

        @Override

        public Item next() {

            if (!hasNext())

                throw new NoSuchElementException();

            

            Item item = current.item;

            current = current.next;

            return item;

        }

        

        @Override

        public void remove() {

            throw new UnsupportedOperationException();

        }

    }

    

    @Override

    public Iterator<Item> iterator() {

        return new 
展开阅读全文