zoukankan      html  css  js  c++  java
  • 栈(Java实现)

    栈是最基本的数据结构之一,其特点是先进后出

    1.基于数组的可动态调节大小的栈

    public class ResizingArrayStack<Item>
    {
        private Item[] a;
        private int N;
    
        public ResizingArrayStack(int cap)
        {
            a = (Item[]) new Object[cap];
        }
    
        private void resize(int max)
        { // 将栈移动到一个大小为max的新数组
            Item[] temp = (Item[]) new Object[max];
            for (int i = 0; i < N; i++)
            {
                temp[i] = a[i];
            }
            a = temp;
        }
    
        public boolean isEmpty()
        {
            return N == 0;
        }
    
        public int size()
        {
            return N;
        }
    
        public void push(Item item)
        { // 将元素添加到栈顶
            if (N == a.length)
            {
                resize(2 * a.length);
            }
            a[N++] = item;
        }
    
        public String pop()
        { // 从栈顶删除元素
            String item = (String) a[--N];
            a[N] = null;// 避免对象游离
            if (N > 0 && N == a.length / 4)
            {
                resize(a.length / 2);
            }
            return item;
        }
    }

    2.基于链表的栈

    public class LinkedListStack<Item>
    {
        private Node first;    //栈顶
        private int N;        //元素数量
        
        private class Node
        {    //定义了结点的嵌套类
            Item item;
            Node next;
        }
        
        public boolean isEmpty()
        {
            return first==null;    //或者N==0
        }
        
        public int size()
        {
            return N;
        }
        
        public void push(Item item)
        {    //向栈顶添加元素
            Node oldfirst=first;
            first=new Node();
            first.item=item;
            first.next=oldfirst;
            N++;
        }
        
        public Item pop()
        {    //从栈顶删除元素
            Item item=first.item;
            first=first.next;
            N--;
            return item;
        }
    }
  • 相关阅读:
    Java 密码扩展无限制权限策略文件
    深入浅出Mybatis系列(八)---mapper映射文件配置之select、resultMap
    git 常用功能 _fei
    ActiveMQ 使用
    【dp】导弹拦截
    【dp】求最长上升子序列
    【贪心】1225 金银岛
    最大子矩阵
    归并排序求逆序对
    服务器安全部署文档
  • 原文地址:https://www.cnblogs.com/yahuian/p/10745004.html
Copyright © 2011-2022 走看看