Java栈的实现

一.栈的元素

一个数组:用来储存数据,数组有个长度就是栈的容量。

一个标志位:栈顶top,这也是栈目前的容量。

二.栈的操作

非常简单,入栈和出栈。下面给出测试。


package datastructure.list;

/**
 ****************************
 * TODO 这里使用字符站后面还有题
 * 
 * @author Chen Fan
 * @version 1.0 time 2021年12月22日
 ****************************
 */

public class CharStack {
	/**
	 * The depth.
	 */
	public static final int MAX_DEPTH = 10;

	/**
	 * The actual depth
	 */
	int depth;

	// 数据用一个数组来装
	char[] data;

	/**
	 * ******************** 初始化栈
	 *********************
	 */
	public CharStack() {
		depth = 0;
		data = new char[MAX_DEPTH];
	}// Of the first constructor

	/**
	 * 
	 *********************
	 * TODO Overrides the methd claimed in Object, the superclass of class.
	 * 
	 * @return String
	 *********************
	 */
	public String toString() {
		String resultString = "";
		for (int i = 0; i < depth; i++) {
			resultString += data[i];
		} // Of for i

		return resultString;
	}// Of toString

	/**
	 * 
	 *********************
	 * TODO Push an element
	 * 
	 * @param paraChar
	 * @return The result is true or false.
	 *********************
	 */
	public boolean push(char paraChar) {
		if (depth == MAX_DEPTH) {
			System.out.println("Stack is full.");
			return false;
		} // Of if

		data[depth] = paraChar;
		depth++;
		return true;
	}

	/**
	 * 
	 *********************
	 * TODO Pop an element
	 * 
	 * @return The top of the element , if no element return ' '
	 *********************
	 */
	public char pop() {
		if (depth == 0) {
			System.out.println("Nothing to pop.");
			return '\0';
		} // Of if

		char resultChar = data[depth - 1];
		depth--;

		return resultChar;
	}// Of pop

	public static void main(String args[]) {
		// 创建一个栈的引用并且指向新值
		CharStack tempStack = new CharStack();

		for (char ch = 'a'; ch < 'm'; ch++) {
			tempStack.push(ch);
			System.out.println("The current stack is: " + tempStack);
		} // Of for ch

		char tempChar;
		for (int i = 0; i < 12; i++) {
			tempChar = tempStack.pop();
			System.out.println("Poped: " + tempChar);
			System.out.println("The current stack is: " + tempStack);
		} // Of for i
	}// Of main
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值