zoukankan      html  css  js  c++  java
  • [数据结构]Java 使用栈结构实现历史列表

    Java提供了一个栈的抽象类、继承过来 实现一下就可以了、

    因为是“历史列表”、所以泛型我用了String类型、仅以记录

     1 import java.util.Arrays;
    2 import java.util.EmptyStackException;
    3 import java.util.Stack;
    4
    5 //栈结构实现类似“历史列表”
    6 public class StackDemo extends Stack<String> {
    7 private String[] list; // 保存元素的列表
    8 private int position = -1; // 记录位置
    9
    10 private boolean autoChangeList = true; // 是否自动扩容、
    11
    12 public StackDemo() {
    13 this(20);
    14 }
    15
    16 public StackDemo(int lenth) {
    17 list = new String[lenth];
    18 }
    19
    20 // 检查是否需要自动扩容
    21 private void checkArray() {
    22 if (autoChangeList) {
    23 if (position > (list.length * 0.75)) {
    24 list = Arrays.copyOf(list, list.length * 2);
    25 }
    26 }
    27 }
    28
    29 @Override
    30 public String push(String item) {
    31 // TODO Auto-generated method stub
    32 checkArray();
    33 list[++position] = item;
    34 return item;
    35 }
    36
    37 @Override
    38 public synchronized String peek() {
    39 // TODO Auto-generated method stub
    40 if (this.empty())
    41 throw new EmptyStackException();
    42 return list[position];
    43 }
    44
    45 @Override
    46 public synchronized String pop() {
    47 // TODO Auto-generated method stub
    48 if(this.empty())
    49 throw new EmptyStackException();
    50 String item = list[position];
    51 list[position--] = null;
    52 return item;
    53 }
    54
    55 @Override
    56 public boolean empty() {
    57 // TODO Auto-generated method stub
    58 return position < 0;
    59 }
    60
    61 @Override
    62 public synchronized int search(Object o) {
    63 // TODO Auto-generated method stub
    64 for (int i = position; i > -1; i--) {
    65 if (list[i].equals(o))
    66 return position - i + 1;
    67 }
    68
    69 return -1; // 不存在栈中 返回-1
    70 }
    71 }



    My New Blog : http://blog.fdlife.info/ The more you know, the less you believe.
  • 相关阅读:
    TCP 监控工具 TCPMonitor
    程序员职业规划
    <转>eclipse如何修改dynamic web module version .
    JBoss部属和EJB调用-EJB3.0入门经典学习笔记(2)
    环境配置与JBoss安装-EJB3.0入门经典学习笔记(1)
    【EDA】PCBA丝印尺寸
    【Altium Designer】PCB如何用规则检查
    【Cadence】Gerber之二:钻孔文件设置与生成
    【生产】如何设计生产线
    【EMC】脉冲群Burst
  • 原文地址:https://www.cnblogs.com/ForDream/p/2331021.html
Copyright © 2011-2022 走看看