LinkedStack

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

package com.lab1.test1;

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

public class LinkedStack implements Iterable {
    private int n;
    private Node first;

    private class Node {
        private Item item;
        private Node next;
    }

    @Override
    public Iterator iterator() {
        return new ListIterator();
    }

    private class ListIterator implements Iterator {
        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 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)