zoukankan      html  css  js  c++  java
  • java实现栈的数据结构

    栈是一种数据结构,只能从一端进行存储和访问。常规操作有压入栈和弹出栈。 
    特性:先进先出,LIFO 
    以下是用ArrayList为内核实现一个栈的数据结构 

    import java.util.ArrayList;
    import java.util.List;
    import java.util.EmptyStackException;
    
    public class Statck<E extends Object> {
        private List<E> pool = new ArrayList<E>();
    
        public Statck() {
        }
    
        public void clear() {
            pool.clear();
        }
    
        public boolean isEmpty() {
            return pool.isEmpty();
        }
    
        /**
         * 获取栈顶元素
         * */
        public E getTopObjcet() {
            if (isEmpty()) {return null;}
            return pool.get(pool.size()-1);
        }
    
        /**
         * 弹出栈操作
         * */
        public E pop() {
            if (isEmpty()) {throw new EmptyStackException();}
            return pool.remove(pool.size() - 1);
        }
    
        /**
         * 压入栈
         * */
        public void push(E e) {
            if (isEmpty()) {throw new EmptyStackException();}
            pool.add(e);
        }
    
        /**
         * 获取当前栈大小
         * */
        public int getStatckSize() {
            if (isEmpty()) {throw new EmptyStackException();}
            return pool.size();
        }
    
    }

    以链表方式实现一个栈 

    public class Statck<E extends Object> {
        private List<E> pool = new ArrayList<E>();
    
        public Statck() {
        }
    
        public void clear() {
            pool.clear();
        }
    
        public boolean isEmpty() {
            return pool.isEmpty();
        }
    
        /**
         * 获取栈顶元素
         * */
        public E getTopObjcet() {
            if (isEmpty()) {return null;}
            return pool.get(0);
        }
    
        /**
         * 弹出栈操作
         * */
        public E pop() {
            if (isEmpty()) {throw new EmptyStackException();}
            return pool.remove(pool.size() - 1);
        }
    
        /**
         * 压入栈
         * */
        public void push(E e) {
            if (isEmpty()) {throw new EmptyStackException();}
            pool.add(e);
        }
    
        /**
         * 获取当前栈大小
         * */
        public int getStatckSize() {
            if (isEmpty()) {throw new EmptyStackException();}
            return pool.size();
        }
    
    }
  • 相关阅读:
    正则表达式
    字节流和字符流小练习
    File汇总
    java一不容易就容易错的知识点汇总
    a++和++a区别
    线程安全的3种方式
    bs4和css选择器的基本使用
    清点作业情况
    cookie和session的使用
    用post请求制作翻译
  • 原文地址:https://www.cnblogs.com/zhujiabin/p/5690774.html
Copyright © 2011-2022 走看看