美文网首页
LinkedStack

LinkedStack

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

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

    package com.lab1.test1;
    
    import java.util.Iterator;
    import java.util.NoSuchElementException;
    
    public class LinkedStack<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 push(Item item) {
            Node oldfirst = first;
            first = new Node();
            first.item = item;
            first.next = oldfirst;
            n++;
        }
    
        private Item pop() {
            if (isEmpty()) {
                throw new NoSuchElementException("empty stack exception");
            }
            Item item = first.item;
            first = first.next;
            n--;
            return item;
        }
    
        public static void main(String[] args) {
            LinkedStack<String> stack = new LinkedStack<>();
            System.out.println(stack);
            System.out.println(stack.size());
            System.out.println(stack.isEmpty());
    
            stack.push("bill");
            stack.push("jack");
            stack.push("lucy");
            System.out.println(stack);
            System.out.println(stack.size());
            System.out.println(stack.isEmpty());
    
            stack.pop();
            stack.pop();
            System.out.println(stack);
            System.out.println(stack.size());
            System.out.println(stack.isEmpty());
        }
    
    }
    

    输出

    
    0
    true
    lucy jack bill 
    3
    false
    bill 
    1
    false
    

    Happy learning !!

    相关文章

      网友评论

          本文标题:LinkedStack

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