算法——背包(后进先出)

来源:互联网 发布:网络骑士流星 编辑:程序博客网 时间:2024/05/18 21:08
public class Bag<Item> implements Iterable<Item> {    private Node first;    private int N;    private class Node{        Item item;        Node next;    }    public void add(Item item){        Node oldfirst = first;        first = new Node();        first.item = item;        first.next = oldfirst;    }    @Override    public Iterator<Item> iterator() {        return new ListIterator();    }    public class ListIterator implements Iterator<Item>{        private Node current = first;        @Override        public boolean hasNext() {            return current != null;        }        @Override        public Item next() {            Item item = current.item;            current = current.next;            return item;        }        @Override        public void remove() {            throw new UnsupportedOperationException();        }    }}

背包只能add,不能pop,通过foreach来遍历。

0 0
原创粉丝点击