用陣列模擬棧的peek,pop,push
阿新 • • 發佈:2018-12-23
public class MyStack<T> {
private int size =10;//初始大小
private int s=0;//指標指到下一個
private Object[] obj;
public MyStack() {
obj = new Object[size];
}
public MyStack(int i) {
size =i;
obj = new Object[size];
}
//壓棧方法
public T push(T t){
//判斷大小,超過擴容,複製新的值
if ((s+2)>size) {
//擴容1.5倍
size=(int) (size*1.5);
Object[] obj2 = new Object[size];
System.arraycopy(obj, 0, obj2, 0, (int)(size/1.5));
obj=obj2;
}
obj[s]=t;
s++;
return t;
}
@SuppressWarnings("unchecked")
public T peek() throws Exception{
if (s<1) {
throw new Exception("不存在元素");
}
T t= (T) obj[s-1];
return t;
}
//出棧方法
@SuppressWarnings("unchecked")
public T pop() throws Exception{
if (s<1) {
throw new Exception("不存在元素");
}
T t= (T) obj[s-1];
obj[--s]=null;
return t;
}
}
private int size =10;//初始大小
private int s=0;//指標指到下一個
private Object[] obj;
public MyStack() {
obj = new Object[size];
}
public MyStack(int i) {
size =i;
obj = new Object[size];
}
//壓棧方法
public T push(T t){
//判斷大小,超過擴容,複製新的值
if ((s+2)>size) {
//擴容1.5倍
size=(int) (size*1.5);
Object[] obj2 = new Object[size];
System.arraycopy(obj, 0, obj2, 0, (int)(size/1.5));
obj=obj2;
}
obj[s]=t;
s++;
return t;
}
@SuppressWarnings("unchecked")
public T peek() throws Exception{
if (s<1) {
throw new Exception("不存在元素");
}
T t= (T) obj[s-1];
return t;
}
//出棧方法
@SuppressWarnings("unchecked")
public T pop() throws Exception{
if (s<1) {
throw new Exception("不存在元素");
}
T t= (T) obj[s-1];
obj[--s]=null;
return t;
}
}