栈--链表实现

栈:后进先出 LIFO
生活实例:先进电梯后出来

存储元素的基本结构:

public class Node {
    /*
    元素有两部分:
    元素的值
    下一个元素的引用
     */
    Object data;//数据域
    Node next; //指针域
    public Node(){}
    public Node(Object data,Node next){
        this.data=data;
        this.next=next;
    }
}

实现栈:

/**
 * Created by yaming
 * 栈的链式存储
 */
public class LinkStack{
    private Node top;//栈顶元素
    private int size;//当前栈大小
    public LinkStack(){
        top=null;
    }

    /**
     * 当前栈的大小
     * @return
     */
    public int length() {
       return size;
    }

    /**
     * 判断栈是否为空
     * @return
     */
    public boolean isEmpty() {
        return size==0?true:false;
    }

    /**
     * 入栈
     * @param data
     * @return
     */
    public boolean push(Object data){
        Node node=new Node(data,null);
        if(isEmpty()){
            top=node;
        }else {
            node.next=top;//把元素放在栈顶,引用指向栈顶
            top=node;
        }
        size++;//元素入栈,栈顶上升
        return true;
    }

    /**
     * 出栈
     * @return
     */
    public Object pop(){
        if(isEmpty()){
            return null;
        }else {
            Node value=top;//得到栈顶元素
            top=top.next;//更新头节点
            value.next=null;//栈顶元素的引用设置为null,该元素被回收
            size--;
            return value.data; //出栈的元素
        }
    }

    /**
     * 返回栈顶元素
     * @return
     */
    public Object peek(){
        if(isEmpty()){
            return null;
        }
        return top.data;
    }

    /**
     * 遍历栈
     * @return
     */
    public String stack(){
        if(isEmpty()){
            return "[]";
        }else {
            StringBuilder stringBuilder=new StringBuilder("[");
            for (Node current=top;current!=null;current=current.next){
                stringBuilder.append(current.data.toString()+", ");
            }
            int length=stringBuilder.length();
            return stringBuilder.delete(length-2,length).append("]").toString();
        }
    }

  public void clear(){
        top=null;
        size=0;
    }
}
原文地址:https://www.cnblogs.com/inspred/p/8052349.html