package aa.bb.cc.demo;
import java.util.Stack;
/**
* Stack的模拟(数组)
* @author 州伟
* @note 用数组模拟一个栈,注意数组是没有变化的,不会删除数组节点,主要是利用top值的变化来实现stack
*/
public class MyStack {
//Stack底层是一个数组(当然也可以list vector等,主要看是否要线程安全????)
private long[] arr;
private int top; //Stack顶
//默认构造方法
public MyStack(){
arr = new long[10];
top = -1;
}
//带参数的构造方法
public MyStack(int maxSize){
arr = new long[maxSize];
top = -1;
}
//添加数据???
public void push(int value){
/**
* 这样理解
* arr[top=top+1] = value;
*/
arr[++top] = value;
}
//移除一个数据???
public long pop(){
/**
* 没有删除的过程??????
*/
return arr[top--];
}
//查看数据???
public long peek(){
return arr[top];
}
//判断是否为空
public boolean isEmpty(){
return top == -1;
}
//判断是否满了
public boolean isFull(){
return top == arr.length -1;
}
/**
* main
* @param args
*/
public static void main(String[] args) {
MyStack ms = new MyStack(4);
ms.push(23);
ms.push(1);
ms.push(90);
ms.push(12);
System.out.println(ms.isEmpty());
System.out.println(ms.isFull());
System.out.println(ms.peek());
System.out.println(ms.peek());
System.out.println();
//先进后出,先出后进
while(!ms.isEmpty()){
System.out.println(ms.pop());
}
System.out.println(ms.isEmpty());
System.out.println(ms.isFull());
System.out.println("--------------自己模拟的stack与JDK中的Stack对比----------------");
//JDK中的Stack
Stack stack = new Stack();
stack.push(23);
stack.push(1);
stack.push(90);
stack.push(12);
System.out.println(stack.isEmpty());
System.out.println(stack.peek());
System.out.println(stack.peek());
System.out.println();
//先进后出,先出后进
while(!stack.isEmpty()){
System.out.println(stack.pop());
}
System.out.println(stack.isEmpty());
}
}
数据结构03.1->Stack栈的模拟(数组)
最新推荐文章于 2024-08-17 16:47:39 发布