Java实现栈数据结构

心血来潮就想用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());
}
}

实现了栈的先进后出的特性,还有栈的自动增长。不过觉得栈的自动增长做的不够好,时间复杂度和空间复杂度应该挺大的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值