模仿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 +
            '}';
}

}
`

上一篇:1078 Hashing


下一篇:Subscriptable Objects in Python