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.
  • 相关阅读:
    [杂说]网络是基础生产工具
    这几天的工作
    [代码]大家来动动脑筋吧
    测试
    [基础] 如何使用extern和static限定符
    元宵节快乐
    复杂的“人"
    C# SMTP发邮件不支持465端口的解决方案,网易企业邮箱
    软件三层架构模型
    ASP.NET MVC 使用二级域名来注册Area区域
  • 原文地址:https://www.cnblogs.com/ForDream/p/2331021.html
Copyright © 2011-2022 走看看