Java栈的简单实现

 * 数据结构与算法Java实现 栈
 * 
 * @author 小明
 *
 */
public class MyStack {
    private Node top;// 头指针
    int size;// 长度

    public MyStack() {
        top = null;
        size = 0;
    }

    // 进栈函数
    public void push(Node node) {
        if (size == 0) {// 栈为空时
            top = node;
            size++;
        } else {// 栈不为空时
            node.setNext(top);
            top=node;
            size++;
        }
    }
    //出栈函数
    public void pop() throws IndexException {
        if(size==0) {
            throw new IndexException("索引错误!");
        }else {
            top=top.getNext();//出栈
            size--;
        }
    }
    @Override
    public  String toString() {
        String str=" ";
        Node temp=top;
        while(temp!=null){
            str+=temp.getElement()+" ";
            temp=temp.getNext();
        }
        str="["+str+" ]";
        return str;
    }
    public static void main(String[] args) throws IndexException {
        MyStack mystack=new MyStack();
        mystack.push(new Node(0));
        mystack.push(new Node(1));
        mystack.push(new Node(2));
        mystack.pop();
        mystack.push(new Node(3));
        System.out.println(mystack);
    }
}

class Node<T> {
    private T element;// 元素
    private Node next;// 后继

    public Node(T element) {// 初始化函数
        this.element = element;
        this.next = null;
    }

    public void setNext(Node node) {
        this.next = node;
    }

    public Node getNext() {
        return next;
    }

    public T getElement() {
        return element;
    }
}

/*
 * 索引异常类
 */
class IndexException extends Exception {
    public IndexException() {

    }

    public IndexException(String s) {
        super(s);
    }
}
原文地址:https://www.cnblogs.com/SAM-CJM/p/9307278.html