zoukankan      html  css  js  c++  java
  • 基于链表的栈(Java)

    package com.rao.linkList;
    
    /**
     * @author Srao
     * @className LinkedStack
     * @date 2019/12/3 13:59
     * @package com.rao.linkList
     * @Description 基于链表的栈
     */
    public class LinkedStack {
    
        /**
         * 定义节点
         */
        static class Node{
            private String data;
            private Node next;
    
            public Node(String data) {
                this.data = data;
                this.next = null;
            }
    
            public String getData() {
                return data;
            }
        }
    
        //栈顶元素
        private Node top;
    
        /**
         * 入栈
         * @param s
         */
        public void push(String s){
            Node node = new Node(s);
            if (top == null){
                top = node;
            }else {
                node.next = top;
                top = node;
            }
        }
    
        /**
         * 出栈
         * @return
         */
        public Node pop(){
            Node node = null;
            if (top.next != null){
                node = top;
                top = top.next;
            }else {
                node = top;
                top = null;
            }
            return node;
        }
    
        public static void main(String[] args) {
            LinkedStack linkedStack = new LinkedStack();
            linkedStack.push("aa");
            linkedStack.push("11");
            linkedStack.push("@@");
            System.out.println(linkedStack.top.getData());
            System.out.println(linkedStack.pop().getData());
            System.out.println(linkedStack.pop().getData());
            System.out.println(linkedStack.pop().getData());
        }
    }

    基于链表的栈和基于数组的栈不同,基于链表的栈必须自己定义节点,而基于数组的栈由数组作为节点,对于节点的定义可以使用内部类来实现,每新建一个类的实例都是新建一个新的节点

  • 相关阅读:
    jupyterlab数据处理
    系统监测模块
    登录验证码的实现
    编码格式检测chardet模块
    图像处理pillow模块
    内存数据的读取
    力扣(LeetCode)728. 自除数
    力扣(LeetCode)709. 转换成小写字母
    Java 层序创建和遍历二叉树
    力扣(LeetCode) 849. 到最近的人的最大距离
  • 原文地址:https://www.cnblogs.com/rao11/p/11976452.html
Copyright © 2011-2022 走看看