1.首先定义了栈需要实现的接口
public interface Mystack<T> { boolean isempty(); void clear(); int length(); //入栈 boolean push(T data); //出栈 T pop(); }
2.栈的数组实现
package suanfa; public class MyArrayStack<T> implements Mystack<T> { private Object [] obs=new Object[16]; private int size=0; @Override public boolean isempty() { // TODO Auto-generated method stub return size==0; } @Override public void clear() { // TODO Auto-generated method stub for (int i=0;i<obs.length;i++){ obs[i]=null; } size=0; } @Override public int length() { // TODO Auto-generated method stub return size; } @Override public boolean push(T data) { // TODO Auto-generated method stub // return false; if(size>=obs.length){ resize(); } obs[size++]=data; return true; } @Override public T pop() { // TODO Auto-generated method stub
if(size==0){
return null;
}
return (T) obs[--size];
} private void resize(){ Object [] tmp=new Object[obs.length*3/2+1]; for(int i=0;i<obs.length;i++){ tmp[i]=obs[i]; obs[i]=null; } obs=tmp; } }
时间: 2024-10-12 11:52:22