心血来潮就想用java实现一个栈的数据结构
1.自定义栈类
package edu.tcu.soft;
public class MyStack<E> {
private Object[] object=new Object[10];
private int top;// 栈顶指针
public MyStack() {
this.top = -1;
}
// 入栈操作
public void push(E item) {
// 确保栈中有足够的空间
// 入栈
if (top==object.length - 1) {
object=increaseStack(object);//栈满时,自动增加栈的深度
} else {
object[++top] = item;
}
}
// 出栈操作
@SuppressWarnings("unchecked")
public E pop() {
// 确保栈非空
// 弹出栈顶元素
if (top == -1) {
System.out.println("栈为空");
return null;
} else {
return (E) object[top--];
}
}
// 获取栈顶元素
@SuppressWarnings("unchecked")
public E peek() {
// 确保栈非空
// 获取栈顶元素
if (top == -1) {
System.out.println("栈为空");
return null;
} else {
return (E) object[top];
}
}
// 查找某个元素在栈的位置
public int search(E item) {
// 栈非空
// 查找在栈的位置
for (int i = top; i >-1; i--) {
if(object[i].equals(item)){
return i;
}
}
return -1;
}
// 栈是否为空
public boolean empty() {
if (top == -1)
return true;
return false;
}
//当栈的空间满的时候自动增长一倍的空间
public Object[] increaseStack(Object[] object){
Object[] ob=new Object[object.length*2];
for(int i=0,j=0;i<ob.length&&j<object.length;i++,j++){
ob[i]=object[i];
}
return ob;
}
public int getObLength(){
return object.length;
}
}
2.测试类
package edu.tcu.soft;
public class Test {
public static void main(String[] args) {
MyStack<Integer> stack=new MyStack<Integer>();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
stack.push(6);
stack.push(7);
stack.push(8);
stack.push(9);
stack.push(10);
stack.push(11);
stack.push(12);
System.out.println(stack.pop()+"---");
System.out.println(stack.pop()+"---");
System.out.println(stack.pop()+"---");
System.out.println("栈的深度:"+stack.getObLength());
}
}
实现了栈的先进后出的特性,还有栈的自动增长。不过觉得栈的自动增长做的不够好,时间复杂度和空间复杂度应该挺大的。