public interface Stack<T> {
/**判断是否为空*/
public boolean isEmpty();
/**清空栈*/
public void clear();
/**弹栈*/
public T pop();
/**像栈中放入元素*/
public boolean push(T data);
/**返回栈的长度*/
public int length();
/**查找栈顶元素*/
public T peek();
/**查找元素*/
public int search(T t);
}
package com.test.stack;
public class ArrayStack<T> implements Stack<T> {
private T[] t = (T[]) new Object[1];
private int size = 0;
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public void clear() {
for (int i = 0; i < size; i++) {
this.t[i] = null;
}
size = 0;
}
/**
* 出栈
*/
@Override
public T pop() {
if (size == 0) {
return null;
} else {
T t = this.t[size - 1];
size--;
return t;
}
}
@Override
public boolean push(T data) {
if (size >= this.t.length) {
// 扩容
resize();
}
this.t[size] = data;
size++;
return true;
}
private void resize() {
T[] temp = (T[]) new Object[this.t.length * 2];
for (int i = 0; i < this.t.length; i++) {
temp[i] = this.t[i];
this.t[i] = null;
}
this.t = temp;
temp = null;
}
@Override
public int length() {
return size;
}
/** 查找栈顶元素,并不删除 */
@Override
public T peek() {
if (size == 0) {
return null;
}
return this.t[size - 1];
}
@Override
public int search(T t) {
for (int i = 0; i < size; i++) {
if (t.equals(this.t[i])) {
return i + 1;
}
}
return 0;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("ArrayStack\n[\n");
for (int i = size - 1; i >= 0; i--) {
sb.append(" " + this.t[i]);
sb.append("\n");
}
sb.append("]");
return sb.toString();
}
public static void main(String[] args) {
ArrayStack<String> arrayStack = new ArrayStack<String>();
arrayStack.push("a");
arrayStack.push("b");
arrayStack.push("c");
arrayStack.push("d");
arrayStack.push("f");
System.out.println(arrayStack.toString());
System.out.println("长度:" + arrayStack.length());
System.out.println("查找:" + arrayStack.search("b"));
System.out.println("查看栈顶元素:" + arrayStack.peek());
System.out.println("弹出栈顶元素:" + arrayStack.pop().toString());
System.out.println("弹出栈顶元素后的长度:" + arrayStack.length());
arrayStack.clear();
System.out.println("删除栈后查看长度:" + arrayStack.length());
System.out.println("删除后的栈"+arrayStack.toString());
}
}