java模拟栈的实现1

用java模拟栈的功能;先进后出。

包结构:



功能实现:

package stackStu;

import java.util.ArrayList;
import java.util.List;

/**
 * java模拟的栈类
 * Created by admin on 2017/2/15.
 */
public class Stack {

    /**
     * 栈的内存区域可以用其他的如 数组 map等等等等
     */
    private List<String> stringList;

    /**
     * 记录集合的最大的下标
     */
    private int maxIndex;

    public Stack() {
        this.stringList = new ArrayList<>();
        this.maxIndex = -1;
    }

    /**
     * 向栈中添加数据
     * @param str 栈中需要添加的数据
     */
    public void Push(String str){
        stringList.add(++maxIndex,str);
    }


    /**
     * 获取栈中的数据,如果没有数据就返回null.
     * @return 返回的栈的最顶端的数据。
     */
    public String Pop(){
        if (maxIndex < 0){
            return null;
        }
        String str = this.stringList.get(maxIndex);
        this.stringList.remove(maxIndex--);
        return str;
    }

    @Override
    public String toString() {
        return "Stack{" +
                "stringList=" + stringList +
                ", maxIndex=" + maxIndex +
                '}';
    }
}

调用:

package stackStu;

/**
 * java 模拟栈的主函数
 * Created by admin on 2017/2/15.
 */
public class StackMain {

    public static void main(String... args){
        Stack stack = new Stack();
        sysPrint(stack);
        //向栈中循环添加数据
        for (int i = 0 ; i < 10 ; i++){
            stack.Push(String.valueOf(i));
        }
        sysPrint(stack);
        //打印所有的栈的数据
        String str =null;
        do{
            str = stack.Pop();
            sysPrint(str);
            sysPrint(stack);
        }while (str != null);
    }

    private static void sysPrint(Stack stack) {
        System.out.println(stack.toString());
    }


    private static void sysPrint(String str) {
        System.out.println(str);
    }

}

打印输出:

Stack{stringList=[], maxIndex=-1}
Stack{stringList=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], maxIndex=9}
9
Stack{stringList=[0, 1, 2, 3, 4, 5, 6, 7, 8], maxIndex=8}
8
Stack{stringList=[0, 1, 2, 3, 4, 5, 6, 7], maxIndex=7}
7
Stack{stringList=[0, 1, 2, 3, 4, 5, 6], maxIndex=6}
6
Stack{stringList=[0, 1, 2, 3, 4, 5], maxIndex=5}
5
Stack{stringList=[0, 1, 2, 3, 4], maxIndex=4}
4
Stack{stringList=[0, 1, 2, 3], maxIndex=3}
3
Stack{stringList=[0, 1, 2], maxIndex=2}
2
Stack{stringList=[0, 1], maxIndex=1}
1
Stack{stringList=[0], maxIndex=0}
0
Stack{stringList=[], maxIndex=-1}
null
Stack{stringList=[], maxIndex=-1}

Process finished with exit code 0


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值