zoukankan      html  css  js  c++  java
  • Java通过链表实现栈

    class LinkedStack<T> {
        private Node top;
        private int size;
    
        /**
         * 初始化栈
         */
        public LinkedStack() {
            top = null;
            size = 0;
        }
    
        /**
         * 判断栈是否为空
         * 
         * @return
         */
        public boolean isEmpty() {
            return size == 0;
        }
    
        /**
         * 清空栈元素
         */
        public void clear() {
            top = null;
            size = 0;
        }
    
        /**
         * 获取栈的大小
         * 
         * @return
         */
        public int length() {
            return size;
        }
    
        /**
         * 将一个数据入栈
         * 
         * @param data
         * @return
         */
        public boolean push(T data) {
            Node node = new Node(data);
            node.pre = top;
            top = node;
            size++;
            return true;
        }
    
        /**
         * 将数据出栈,并删除
         * 
         * @return
         */
        public T pop() {
            if (top != null) {
                Node node = top;
                top = top.pre;
                size--;
                return node.data;
            }
            return null;
        }
    
        /**
         * 获取栈顶元素,但不删除该栈元素数据
         * 
         * @return
         */
        public T peek() {
            if (top != null) {
                return top.data;
            }
            return null;
        }
    
        /**
         * 节点类
         * 
         * @author John
         *
         */
        private class Node {
            Node pre;
            T data;
    
            public Node(T data) {
                this.data = data;
            }
        }
    }
  • 相关阅读:
    c++面试题
    MFC 字符串类CString 源代码
    c++ ofstream & ifstream文件流操作
    理解ip和端口
    求解最长回文字符串
    @Document元注解的使用
    JVM、JRE和JDK的理解
    Java发展历程及各版本新特性
    Maven的安装配置
    认识Java注解
  • 原文地址:https://www.cnblogs.com/SaraMoring/p/5794371.html
Copyright © 2011-2022 走看看