Java栈的两种实现

1. 基于数组

package Algorithm.learn;

import java.util.Arrays;

/**
 * Created by liujinhong on 2017/3/7.
 */
public class MyStack<E> {
    private Object[] stack;
    private int size;
    MyStack() {
        stack = new Object[10];
        size = 0;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public E peek() {
        if (isEmpty()) {
            return null;
        }
        return (E)stack[size-1];
    }

    public E pop() {
        if (isEmpty()) {
            return null;
        }
        size--;
        return (E)stack[size];
    }

    private void ensureCapacity(int size) {
        if (size > stack.length) {
            int len = stack.length + 10;
            stack = Arrays.copyOf(stack, len);
        }
    }

    public E push(E e) {
        ensureCapacity(size+1);
        stack[size++] = e;
        return e;
    }

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

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

2. 基于链表

package Algorithm.learn;

/**
 * Created by liujinhong on 2017/3/7.
 */

class Node<E> {
    Node<E> next = null;
    E data;
    public Node(E data) {
        this.data = data;
    }
}

public class ListStack<E> {
    Node<E> top = null;

    boolean isEmpty() {
        return top == null;
    }

    public void push(E item) {
        Node<E> node = new Node<E>(item);
        node.next = top;
        top = node;
    }

    public E pop() {
        if (this.isEmpty()) return null;
        E data = top.data;
        top = top.next;
        return data;
    }

    public E peek() {
        if (this.isEmpty()) return null;
        return top.data;
    }

    public static void main(String[] args) {
        ListStack<Integer> stack = new ListStack<>();
        stack.push(1);
        stack.push(2);

        System.out.println(stack.pop());
        System.out.println(stack.pop());
    }
}
原文地址:https://www.cnblogs.com/liujinhong/p/6513141.html