java实现栈的链式存储

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhblanlan/article/details/81189295

线性表到栈的链式存储的映射
这里写图片描述

代码实现栈的链式存储

package 数据结构;

// 栈的链式存储:优点是不存在栈满的情况
public class LinkStack {
    private Node header = new Node();   // 创建头节点
    class Node {
        String value;
        Node next;      
    }
    /**
     * 将新节点进栈,插入头节点之后
     * @param value
     */
    public boolean push(String value) {
        Node n = new Node();
        n.value = value;
        if(header.next == null) {
            header.next = n;
            return true;
        }
        n.next = header.next;
        header.next = n;
        return true;

    }
    /**
     * 将栈顶元素出栈
     * @return 元素的值
     */
    public boolean pop() {
        if(header.next == null) {
            return false;
        }
        header.next = header.next.next;
        return true;
    }
    /**
     * 获取栈顶元素
     * @return 栈顶元素的值
     */
    public String getTop() {
        if(header.next != null) {
            return header.next.value;
        }
        return null;
    }
    /**
     * 判断栈是否为空
     * @return
     */
    public boolean isEmpty() {
        return header.next == null ? true : false;
    }
    public static void main(String[] args) {
        LinkStack stack = new LinkStack();
        System.out.println(stack.isEmpty());  // 判断栈顶元素是否为空
        stack.push("张三");                   // 进栈
        stack.push("李四");
        stack.push("王五");
        stack.push("赵六");
        System.out.println(stack.isEmpty());
        System.out.println(stack.getTop());  // 获取栈顶元素
        System.out.println(stack.pop());     // 将栈顶元素出栈
        System.out.println(stack.getTop());  // 获取栈顶元素

    }

}

运行结果如下

true
false
赵六
true
王五

猜你喜欢

转载自blog.csdn.net/zhblanlan/article/details/81189295