使用数组实现栈 MyStack

import java.util.ArrayList;
import java.util.List;

public class MyStack<V> {

    private List<V> stack = new ArrayList<V>();
    private int top = -1;

    public boolean isEmpty() {
        return top < 0;
    }

    public void push(V v) {
        top++;
        if (stack.size() > top) {
            stack.set(top, v);
        }
        stack.add(v);
    }

    public V pop() {
        if (isEmpty()) {
            return null;
        }
        return stack.get(top--);
    }

    public static void main(String[] args) {
        MyStack<String> stack = new MyStack<String>();
        stack.push("a");
        stack.push("b");
        stack.push("c");

        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());

        stack.push("d");
        stack.push("e");
        stack.push("f");

        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
    }
}

你可能感兴趣的:(java)