zoukankan      html  css  js  c++  java
  • 使用内部单向链表实现的一个简单堆栈

    使用内部单向链表实现的一个简单堆栈。通过本代码可以对泛型,单向链表及堆栈的实现有较全面的了解。单向链表中的每一个元素(或称节点)中有一个next域指向该元素的下一个元素,这样就可以将多个元素一个个链接起来,形成一个单向链表。

    /**
     * 单向列表实现的简单堆栈
     */
    package generics;
    
    /**
     * 泛型单向堆栈类
     * @author LYL
     *
     */
    public class LinkedStack<T> {
        /**
         * 堆栈中一个节点元素
         * @author LYL
         *
         * @param <U>
         */
        private class Node<U>{
            private U item;
            private Node<U> next;
            public Node(){ this.item=null;this.next=null;}
            public Node(U item,Node<U> next){
                this.item=item;
                this.next=next;
            }
            public boolean end(){
                return item==null && next==null;
            }
        }
        
        //栈顶
        private Node<T> top=new Node<T>();
        /**
         * 入栈
         * @param item
         */
        public void push(T item){
            top=new Node<T>(item,top);
        }
        /**
         * 出栈
         * @return
         */
        public T pop(){
            //取出栈项元素
            T result=top.item;
            if(!top.end()){
                //如果非最后一个节点,则改变栈项
                top=top.next;
            }
            return result;
        }
        public static void main(String[] args){
            LinkedStack<String> stack=new LinkedStack<String>();
            for(String s : "美国,中国".split(",")){
                stack.push(s);
            }
            String s;
            while((s=stack.pop())!=null){
                System.out.println(s);
            }
        }
    }
  • 相关阅读:
    奶酪(NOIP2017 Day2 T1)
    图的遍历(某谷P3916)
    20154331 EXP9web安全基础实践
    20154331 EXP8 web基础
    20154331EXP7 网络欺诈
    20154331 Exp6 信息搜集与漏洞扫描
    Exp5 MSF基础应用
    Exp4 恶意代码分析
    Exp3 免杀原理与实践
    20154331黄芮EXP2 后门原理与实践
  • 原文地址:https://www.cnblogs.com/bjwylpx/p/3679193.html
Copyright © 2011-2022 走看看