用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