Java Bag模型模拟

//背包节点类(布袋节点类)
public class BagNode<Item>{
	Item item; //参数
	BagNode next; //下一个背包节点;
}

import java.util.Iterator;

//定义泛型背包类
public class Bag<Item> implements Iterable<Item> {

	//0定义私有的成员变量;
	private BagNode first;
	
	//1.定义添加背包项方法;
	public void add(Item item){
		BagNode oldFirst=first;
		first.item=item;
		first.next=oldFirst;
	}
	
	@Override
	public Iterator<Item> iterator() {
		return new BagIterator();
	}
	//定义私有的内部类;
	private class BagIterator implements Iterator<Item>{
		
		BagNode node=first;//定义背包第一个节点是first
		@Override
		public boolean hasNext() {
			return node.next!=null;
		}

		@Override
		public Item next() {
			Item item=(Item)node.item;
			node=node.next;
			return item;
		}

		@Override
		public void remove() {
		//背包数据结构不存在删除方法,所以去掉该方法的定义。	
		}
		
	}

}

附上:Robert Sedgewick的源码:可以看到高校立现,佩服!!!

import java.util.Iterator;
import java.util.NoSuchElementException;


public class Bag<Item> implements Iterable<Item> {
    private Node<Item> first;    // beginning of bag
    private int n;               // number of elements in bag

    // helper linked list class
    private static class Node<Item> {
        private Item item;
        private Node<Item> next;
    }

    /**
     * Initializes an empty bag.
     */
    public Bag() {
        first = null;
        n = 0;
    }

    /**
     * Returns true if this bag is empty.
     *
     * @return {@code true} if this bag is empty;
     *         {@code false} otherwise
     */
    public boolean isEmpty() {
        return first == null;
    }

    /**
     * Returns the number of items in this bag.
     *
     * @return the number of items in this bag
     */
    public int size() {
        return n;
    }

    /**
     * Adds the item to this bag.
     *
     * @param  item the item to add to this bag
     */
    public void add(Item item) {
        Node<Item> oldfirst = first;
        first = new Node<Item>();
        first.item = item;
        first.next = oldfirst;
        n++;
    }


    /**
     * Returns an iterator that iterates over the items in this bag in arbitrary order.
     *
     * @return an iterator that iterates over the items in this bag in arbitrary order
     */
    public Iterator<Item> iterator()  {
        return new ListIterator<Item>(first);  
    }

    // an iterator, doesn't implement remove() since it's optional
    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;
        }
    }

    /**
     * Unit tests the {@code Bag} data type.
     *
     * @param args the command-line arguments
     */
    public static void main(String[] args) {
        Bag<String> bag = new Bag<String>();
        while (!StdIn.isEmpty()) {
            String item = StdIn.readString();
            bag.add(item);
        }

        StdOut.println("size of bag = " + bag.size());
        for (String s : bag) {
            StdOut.println(s);
        }
    }

}
//背包的典型用例
public class Stats {
	public static void main(String[] args) {
		Bag<Double>numbers=new Bag<Double>();
		
		
		//while(!StdIn.isEmpty())
		for(int i=0;i<5;i++)
			numbers.add(StdIn.readDouble());
		
		int N=numbers.size();
		
		System.out.println(N);
		double sum=0.0;
		
		for(double x:numbers)
			sum+=x;
		
		double mean=sum/N;
		
		sum=0.0;
		
		for(double x:numbers)
			sum+=(x-mean)*(x-mean);
		
		double std=Math.sqrt(sum/(N-1));
		
		StdOut.printf("Mean: %.2f\n",mean);
		StdOut.printf("Std dev:%.2f\n",std);
	}
}

利用背包求出平均值和样本标准差。

猜你喜欢

转载自blog.csdn.net/zhangchen124/article/details/79818747