栈的基本操作java

简介:

栈也是数据结构中的一种,类似于顺序表和链表,最大的区别就是数据的存储操作。对于栈而言,把允许操作的一端叫做栈顶,只允许对栈顶进行插入和删除,把不可操作的一端称为栈底,它是一种先进后出或后进先出的顺序表。

Java实现的代码

入栈:

	//入栈操作
	public boolean push(char paraChar) {
		if(depth == MAX_DEPTH) {
			System.out.println("Stack full.");
			return false;
		} // of if
		data[depth]=paraChar;
		depth++;
		
		return true;
	}//of push

出栈:

	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 class CharStack {
	/*
	 * The depth.
	 */
	public static final int MAX_DEPTH = 10;
	/*
	 * The actual depth.
	 */
	int depth;
	/*
	 * The data
	 */
	char[] data;

	/*
	 * Construct an empty char stack.
	 */
	public CharStack() {
		depth = 0;
		data = new char[MAX_DEPTH];
	}// of the first constructor

	/*
	 * Overrides the method claimed in object, the superclass of any class.
	 */
	public String toString() {
		String resultString = "";
		for (int i = 0; i < depth; i++) {
			resultString += data[i];
		} // of for i
		return resultString;
	}// of toString
		// 入栈操作

	public boolean push(char paraChar) {
		if (depth == MAX_DEPTH) {
			System.out.println("Stack full.");
			return false;
		} // of if
		data[depth] = paraChar;
		depth++;

		return true;
	}// of push

	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
}// of charStack

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值