LinkedBag

作者: 賈小強 | 来源:发表于2018-03-28 11:05 被阅读12次

    简书 賈小強
    转载请注明原创出处,谢谢!

    package com.lab1.test1;
    
    import java.util.Iterator;
    
    public class LinkedBag<Item> implements Iterable<Item> {
        private int n;
        private Node first;
    
        private class Node {
            private Item item;
            private Node next;
        }
    
        @Override
        public Iterator<Item> iterator() {
            return new ListIterator();
        }
    
        private class ListIterator implements Iterator<Item> {
            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 String toString() {
            StringBuilder builder = new StringBuilder();
            for (Item item : this) {
                builder.append(item + " ");
            }
            return builder.toString();
        }
    
        private boolean isEmpty() {
            return first == null;
        }
    
        private int size() {
            return n;
        }
    
        private void add(Item item) {
            Node oldfirst = first;
            first = new Node();
            first.item = item;
            first.next = oldfirst;
            n++;
        }
    
        public static void main(String[] args) {
            LinkedBag<String> bag = new LinkedBag<>();
            System.out.println(bag);
            System.out.println(bag.size());
            System.out.println(bag.isEmpty());
            
            bag.add("bill");
            bag.add("jack");
            bag.add("lucy");
            System.out.println(bag);
            System.out.println(bag.size());
            System.out.println(bag.isEmpty());
        }
    
    }
    

    输出

    
    0
    true
    lucy jack bill 
    3
    false
    

    Happy learning !!

    相关文章

      网友评论

          本文标题:LinkedBag

          本文链接:https://www.haomeiwen.com/subject/sicycftx.html