直接上代码
package com.mydemo.writeCases;
public class IStack<E> {
private E[] elemetData;
private int size;
public IStack(){
this(5);
}
public IStack(int capacity){
this.elemetData = (E[]) new Object[capacity];
}
public int getSize(){
return this.size;
}
public void push(E e){
if (size == elemetData.length) {
resize();
}
elemetData[size] = e;
size++;
}
public E pop(){
if (isEmpty()){
throw new RuntimeException("栈为空");
}
E target = elemetData[size - 1];
elemetData[size - 1] = null;
size--;
return target;
}
public E peek(){
if (isEmpty()){
throw new RuntimeException("栈为空");
}
E target = elemetData[size - 1];
return target;
}
public boolean isEmpty(){
return size == 0;
}
private void resize(){
int newLength = elemetData.length * 2;
E[] newArray = (E[]) new Object[newLength];
System.arraycopy(elemetData,0,newArray,0,size);
elemetData = newArray;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < size; i++) {
builder.append("[" + (elemetData[i] == null ? "null" : elemetData[i]) + "]");
}
return builder.toString();
}
public static void main(String[] args) {
IStack<String> stack = new IStack<>();
stack.push("2");
stack.push("3");
stack.push("4");
stack.push("4");
stack.push("4");
stack.push("6");
stack.push("7");
String pop = stack.pop();
stack.push("5");
stack.peek();
boolean empty = stack.isEmpty();
}
}