Java数据结构之栈的实现

Java实现栈:

import java.util.Arrays;

public class Stack<T> {
	private Object[] elem;// 使用数组实现
	private int top;// 指向栈顶元素的指针

	public Stack(int size) {
		if (size < 1) {
			size = 10;// 若用户输入错误大小,默认大小为10
		}
		this.elem = new Object[size];
		this.top = -1;// 栈中无元素,top为-1
	}

	// 清空栈中的元素
	public void clear() {
		Arrays.fill(elem, null);
		top = -1;
	}

	// 检查是否为空栈
	public boolean isEmpty() {
		return top == -1;
	}

	// 取栈中元素个数
	public int length() {
		return top + 1;
	}

	// 取栈顶元素
	@SuppressWarnings("unchecked")
	public T top() {
		if (!isEmpty()) {
			return (T) elem[top];
		} else
			throw new RuntimeException("栈为空");
	}

	// 入栈
	public boolean push(T t) {
		if (top == elem.length - 1) {
			throw new RuntimeException("栈已满");
		} else {
			elem[++top] = t;
			return true;
		}
	}

	// 弹出栈顶元素
	public boolean pop() {
		if (isEmpty()) {
			throw new RuntimeException("栈已空");
		} else {
			elem[top--] = null;
			return true;
		}
	}

	// 打印,从栈顶到栈底
	public void print() {
		for (int i = top; i >= 0; i--) {
			System.out.print(elem[i] + " ");
		}
		System.out.println();
	}

    //简单测试
	public static void main(String[] args) {
		Stack<Integer> st = new Stack<Integer>(10);
		st.push(1);
		st.push(5);
		st.print();
		System.out.println("栈顶元素:" + st.top());
		st.pop();
		System.out.println("出栈后栈顶元素:" + st.top());
		System.out.println("栈中元素个数为:" + st.length());
		st.clear();
		for (int i = 0; i < 5; i++) {
			System.out.print(i + ": " + st.elem[i] + " ");
		}
	}
}

​

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值