自己写一个简易版的栈类,用来加深对堆栈的理解,顺便练习一下泛型
package com.sxt;
import java.util.Arrays;
import java.util.EmptyStackException;
public class StackTest {
public static void main(String[] args) {
Stack2 s=new Stack2();
System.out.println(s.empty());
for (int i=0;i<10;i++){
s.push(" "+i);
//System.out.println(s.StackLength);
}
System.out.println(s.size);
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.size);
}
}
class Stack2 {
//初始长度,指针,数组。。。
Object[] arr;
int index=-1;//指针
int StackLength=4;//初始长度
int size=0;//长度
public boolean empty(){
if (index==-1){
return false;
}
return true;
}
public E push(E item){
SetCapacity();
//添加元素
arr[++index]=item;
size++;
return item;
}
private void SetCapacity(){
//初始化数组
if (!empty()){
arr=new Object[StackLength];
}
//判断数组大小是否需要扩容
if (size>((StackLength>>1)+(StackLength>>2))){
StackLength=StackLength+(StackLength>>1);//以1.5倍扩容
arr= Arrays.copyOf(arr,StackLength);//Arrays方法包含对数组的各种操作
}
}
//删除栈顶元素,出栈
public E pop(){
size--;
E item=peek();
index--;
return item;
}
//查看栈顶元素
public E peek(){
if (index==-1){
throw new EmptyStackException();
}
return (E) arr[index];
}
}



