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

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

  • 相关阅读:
    cpu几种架构区别
    linux之cp/scp命令+scp命令详解
    解读Linux命令格式(转)
    IO虚拟化简单了解
    NoSQL-来自维基百科
    kvm命令参数记录
    kvm 简单了解
    host与guest间共享文件夹的三种方法(原创)
    新装linux系统最基本设置
    kernel编译速度提高
  • 原文地址:https://www.cnblogs.com/rao11/p/11976452.html
Copyright © 2011-2022 走看看