其他分享
首页 > 其他分享> > 模仿Stack自定义容器对象MyStack

模仿Stack自定义容器对象MyStack

作者:互联网

`public class MyStack {

private Object[] objects = new Object[10];

private int count;

public boolean empty(){

    for (int i = 0; i < objects.length; i++) {
        if(objects[i] != null){
            return false;
        }
    }
    return true;
}

public Object peek(){
    Object o = null;
    for (int i = 0; i < objects.length; i++) {
        if(objects[i] != null){
            o = objects[i];
        }else{
            break;
        }
    }
   return o;
}

public Object pop(){
    Object o = null;
    int index = 0;
    for (int i = 0; i < objects.length; i++) {
        if(objects[i] != null ){
            o = objects[i];
            index = i;
        }else{
            break;
        }
    }
    Object[] newObjects = new Object[objects.length];
    System.arraycopy(objects,0,newObjects,0,index);
    objects = newObjects;
    count--;
    return o;
}

public void push(Object item){
    if(count==objects.length){
        Object[] newObjects = new Object[count+1];
        System.arraycopy(objects,0,newObjects,0,objects.length);
        objects = newObjects;
    }
    objects[count++]=item;
}

public int search(Object o){
    int index = -1;
    for (int i = 0; i < objects.length; i++) {
        if(objects[i] != null){
            index = i;
        }else{
            break;
        }
    }

    for (int i = 0; i < objects.length; i++) {
        if(objects[i] != null && o == objects[i]){
            return index - i + 1;
        }
    }
    return -1;
}

@Override
public String toString() {
    return "MyStack{" +
            "objects=" + Arrays.toString(objects) +
            ", count=" + count +
            '}';
}

}
`

标签:自定义,int,Object,public,length,objects,MyStack,null,Stack
来源: https://www.cnblogs.com/sharkzzz/p/15774763.html