java揹包的陣列實現,連結串列實現
阿新 • • 發佈:2018-12-07
陣列實現
package base.structure; import java.lang.reflect.Array; import java.util.Iterator; /** * @program: Algorithm4J * @description: 揹包陣列的實現 * @author: Mr.Dai * @create: 2018-12-05 22:56 **/ class Bag<T> implements Iterable<T>{ int n; T [] elements; Bag(){ elements= (T[]) new Object[20]; n=0; } void add(T item){ if(n==elements.length){ T [] new_elements= (T[]) new Object[elements.length*2]; System.arraycopy(elements,0,new_elements,0,elements.length); elements=new_elements; } elements[n++]=item; } boolean isEmpty(){ return n==0; } int Size(){ return n; } @Override public Iterator<T> iterator() { return new BagIterator(); } class BagIterator implements Iterator<T>{ private int i=0; @Overridepublic boolean hasNext() { return i<n; } @Override public T next() { return elements[i++]; } } } public class BagForArray { public static void main(String[] args) { Bag<Integer> bag = new Bag<>(); bag.add(1); bag.add(2); for (int i = 0; i < 3; i++) { bag.add(4); } Iterator<Integer> iterator = bag.iterator(); while (iterator.hasNext()){ System.out.println(iterator.next()); } } }
連結串列的實現
package base.structure; import java.util.Iterator; import java.util.NoSuchElementException; /** * @program: Algorithm4J * @description: 揹包逆序連結串列實現 * @author: Mr.Dai * @create: 2018-12-06 10:25 **/ class Bags<T> implements Iterable<T>{ int n; Node<T> fisrt; /** * 構建一個連結串列類 * @param <T> */ private static class Node<T>{ T val; Node<T> next; } /** * 有頭結點才能正序取到值 */ Bags(){ fisrt=null; n=0; } void add(T item){ Node<T> old_Node=fisrt; fisrt=new Node<>(); fisrt.val=item; fisrt.next=old_Node; n++; } boolean isEmpty(){ return fisrt==null; } int Size(){ return n; } @Override public Iterator<T> iterator() { return new BagsIterator(fisrt); } class BagsIterator implements Iterator<T>{ private Node<T> current; BagsIterator(Node<T> item){ current=item; } public void remove(){ throw new UnsupportedOperationException(); } @Override public boolean hasNext() { return current!=null; } @Override public T next() { if(!hasNext()) throw new NoSuchElementException(); T item=current.val; current=current.next; return item; } } } public class BagForLinked { public static void main(String[] args) { Bags<String> bag=new Bags<>(); bag.add("a"); bag.add("b"); bag.add("c"); bag.add("d"); for (String s : bag) { System.out.println(s); } } }