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());
        }
    }

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

  • 相关阅读:
    Node.js :HTTP请求和响应流程
    Node.js :URL、QueryString介绍
    jQuery
    如何angular过滤器进行排序???
    封装jsonp
    原生js的math对象
    Iscrool下拉刷新
    javascript闭包
    javascript对象(3)
    javascript对象(2)
  • 原文地址:https://www.cnblogs.com/rao11/p/11976452.html
Copyright © 2011-2022 走看看